Laravel 5.4 : 使用模型继承从 child object 中获取 parent object
Laravel 5.4 : get parent object from the child object using Model Inheritance
我正在使用 Laravel 5.4。
我面临的问题是关于模型继承。
以下是 2 classes 的代码片段:
class Company extends Model{
protected $table = 'companies';
}
class Vendor extends Company{
protected $table = 'companies';
}
注意:这里的公司是parentclass,供应商是childclass。此外,两个模型都引用相同的 table.
我有 供应商 class 的 object(即 child class)。
例如:
$vendor = Vendor::find(1);
如何从现有的供应商 object 处获得公司 object?
因为两者都引用数据库中的相同记录。
您可以通过在关系方法中指定 field/column 名称来解决您的问题。您可以在声明关系方法时指定确切的键,这样 Laravel
就不会使用它的约定来映射 model/table,例如,您可以在 Company
模型中使用以下语法是many-to-many
关系方法:
class Company extends Model
{
public function someMethod()
{
return $this->belongsToMany(
'App\OtherModel', // name of the other model
'pivot_table_name', // name of the pivot table
'company_id' // this model foreign key
'other_model_foreign_key' // other model foreign key
);
}
}
在这种情况下,外键应与您的数据透视 table 中使用的 field/column 名称相匹配。现在你可以从 Vendor
对象的实例调用你的关系方法 (someMethod
) 并且它会工作得很好,因为指定了 compoany_id
所以 Laravel
将使用该列名vendor_id
。查看更多关于 many-to-many relationship.
我正在使用 Laravel 5.4。
我面临的问题是关于模型继承。
以下是 2 classes 的代码片段:
class Company extends Model{
protected $table = 'companies';
}
class Vendor extends Company{
protected $table = 'companies';
}
注意:这里的公司是parentclass,供应商是childclass。此外,两个模型都引用相同的 table.
我有 供应商 class 的 object(即 child class)。
例如:
$vendor = Vendor::find(1);
如何从现有的供应商 object 处获得公司 object? 因为两者都引用数据库中的相同记录。
您可以通过在关系方法中指定 field/column 名称来解决您的问题。您可以在声明关系方法时指定确切的键,这样 Laravel
就不会使用它的约定来映射 model/table,例如,您可以在 Company
模型中使用以下语法是many-to-many
关系方法:
class Company extends Model
{
public function someMethod()
{
return $this->belongsToMany(
'App\OtherModel', // name of the other model
'pivot_table_name', // name of the pivot table
'company_id' // this model foreign key
'other_model_foreign_key' // other model foreign key
);
}
}
在这种情况下,外键应与您的数据透视 table 中使用的 field/column 名称相匹配。现在你可以从 Vendor
对象的实例调用你的关系方法 (someMethod
) 并且它会工作得很好,因为指定了 compoany_id
所以 Laravel
将使用该列名vendor_id
。查看更多关于 many-to-many relationship.