如何通过模型 ID 和模型类型在 laravel 中创建关系
how to create relationship in laravel by model id and model types
我有一个与一个关联的 table,使用他们的 id 和 id table type
table 1
id,
type_id,
类型,
数数,
crteated_at,
updated_at
其他tables
id 姓名,......crteated_atupdated_at
模型类型 ID
模型2 = type_id = 2;
模型 3 = type_id = 3;
In model 1
public function model2()
{
return $this->belongsTo(model2::class, 'type_id', 'id');
}
public function model3()
{
return $this->belongsTo(model3::class, 'type_id', 'id');
}
你应该使用多态关系:
https://laravel.com/docs/5.5/eloquent-relationships#polymorphic-relations
public function getModel(Request $request){
if($request->get('model_type')==1){
$mod = 'Model1'
}
if($request->get('model_type')==2){
$mod = 'Model'
}
$obj = new {Mod}()
$result = $obj->get();
return $result
}
我会这样做
我有一个与一个关联的 table,使用他们的 id 和 id table type
table 1
id, type_id, 类型, 数数, crteated_at, updated_at
其他tables
id 姓名,......crteated_atupdated_at
模型类型 ID
模型2 = type_id = 2; 模型 3 = type_id = 3;
In model 1
public function model2()
{
return $this->belongsTo(model2::class, 'type_id', 'id');
}
public function model3()
{
return $this->belongsTo(model3::class, 'type_id', 'id');
}
你应该使用多态关系:
https://laravel.com/docs/5.5/eloquent-relationships#polymorphic-relations
public function getModel(Request $request){
if($request->get('model_type')==1){
$mod = 'Model1'
}
if($request->get('model_type')==2){
$mod = 'Model'
}
$obj = new {Mod}()
$result = $obj->get();
return $result
}
我会这样做