I have the following structure:
branch_has_language table represents the ManyToMany relationship between the languages and branches. On the other hand a product belongs to a branch_has_language record. So the product can be created for specific language and branch, where they 'exist' together in branch_has_language table.
My question is how to create the model in order to represent this relationship. Currently I have the following model:
class Branch extends Model
{
protected $table = "branches";
public function languages()
{
return $this->belongsToMany("\App\Language", "branch_has_language");
}
public function users()
{
return $this->belongsToMany("\App\User", "branch_has_user");
}
public function newPivot(Model $parent, array $attributes, $table, $exists) {
if ($parent instanceof Language) {
return new BranchLanguage($parent, $attributes, $table, $exists);
}
return parent::newPivot($parent, $attributes, $table, $exists);
}
}
class Language extends Model
{
protected $table = "languages";
public function branches()
{
return $this->belongsToMany("\App\Branch", 'branch_has_language');
}
public function newPivot(Model $parent, array $attributes, $table, $exists) {
if ($parent instanceof Branch) {
return new BranchLanguage($parent, $attributes, $table, $exists);
}
return parent::newPivot($parent, $attributes, $table, $exists);
}
}
class BranchLanguage extends Pivot
{
protected $table = 'branch_has_language';
public function branch()
{
return $this->belongsTo("\App\Branch");
}
public function language()
{
return $this->belongsTo("\App\Language");
}
public function products()
{
return $this->hasMany("\App\Product");
}
public function systems()
{
return $this->hasMany("\App\System");
}
public function items()
{
return $this->hasMany("\App\Item");
}
}
However when I want to make a call to products() method in BranchLanguage class, I got an error saying " Column products.branch_id does not exists". This is correct. I need to specify the foreign key in the hasMany() method. However my foreign key is composite. branch_has_language_branch_id and branch_has_language_language_id columns build up the foreign key. Therefore I could not define it in the hasMany() method.
Could you please help me to solve this problem?
from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1NTXdNV
via IFTTT
Aucun commentaire:
Enregistrer un commentaire