领导桌
员工表
管理员表
$users = Leads::query();
return Datatables::make($users)
->editColumn('owner_id', function ($user) {
if($user->from_table == 'employee'){
$emp = Employee::where('id',$user->owner_id)->first();
return $emp->first_name.' '.$emp->last_name.' ('.$emp->role.')';
}
if($user->from_table == 'admin'){
$admin = Admin::where('id',$user->owner_id)->first();
return $admin->first_name.' '.$admin->last_name.' ('.$admin->role.')';
}
})
上述解决方案效果很好,但是我们无法在数据表中搜索按列进行的个性化搜索。
我想要的是加入查询之类的东西
if(leads.from_table ==员工) //从EMPLOYEE TABLE中提取数据,即LEADS TABLE + EMPLOYEE TABLE
if(leads.from_table == admin) //从ADMIN TABLE中获取数据,即LEADS TABLE + ADMIN TABLE
答案 0 :(得分:0)
我认为您应该更改数据库结构以使用多态关系,它们完全符合您的需求-https://laravel.com/docs/5.8/eloquent-relationships#polymorphic-relationships
答案 1 :(得分:0)
from_table列应包含父模型的类名称。
Add in Leads model
public function fetchOwner()
{
return $this->morphTo();
}
添加员工模型
public function employee()
{
return $this->morphOne('App\Employee', 'fetchOwner');
}
添加管理模型
public function employee()
{
return $this->morphOne('App\Admin', 'fetchOwner');
}
$users = Leads::with('fetchOwner');
return Datatables::make($users)
->editColumn('owner_id', function ($user) {
return $user->fetchOwner->name;
})
答案 2 :(得分:0)
感谢所有试图提供帮助的人。
我正在回答自己的问题,因为我到处挖了9天才找到答案。
所以这是答案:
you may want to replace owner_code by owner_id in your business table.
所以我将from_table更改为owner_type和owner_type,现在应包含类名,例如值:在数据库中将admin更改为App \ Admin,并将employee更改为App \ Employee
App\Admin.php
public function employee()
{
return $this->morphOne('App\Leads', 'owner');
}
App\Employee.php
public function employee()
{
return $this->morphOne('App\Leads', 'owner');
}
App\Leads.php
public function owner()
{
return $this->morphTo();
}
感谢:laravel morphTo how to use custom columns?(EddyTheDove)指出了确切的问题。