我正在使用https://datatables.net/examples/server_side/simple.html
中的数据表,并且能够将所有信息显示到表中。
此处是Howeber,而不是Member Source列中的外键,我希望这些Name从与ID匹配的另一个表中出现 我的会员模型是:
class Member extends Model
{
protected $fillable = ['name','mobile_number','organization_name','source_of_member','relationship_manager','referred_by'];
public function memberSource()
{
return $this->hasOne('App\MemberSource', 'id');
}
}
我的memberSource模型为:
class MemberSource extends Model
{
protected $fillable = ['name'];
public function member()
{
return $this->hasOne('App\Member', 'id');
}
}
我尝试过的是:
public function getdata()
{
$members = Member::all();
return Datatables::of($members)
->addColumn('action', function($member){
return '<a data-id="'.$member->id.'" href="#" data-toggle="modal" id="openShow" class="btn btn-info btn-xs"><i class="fas fa-eye"></i></a> ' .
'<a href="member/edit/'.$member->id.'" class="btn btn-primary btn-xs"><i class="fas fa-edit"></i></a> ' .
'<a href="member/delete/'.$member->id.'" class="btn btn-danger btn-xs"><i class="fas fa-trash-alt"></i></a>';
})
->make(true);
}
我不知道该怎么做,将不胜感激。
答案 0 :(得分:2)
在您的会员模型中:
public function memberSource()
{
return $this->hasOne('App\MemberSource', 'source_of_member');
}
在控制器中:
$members = Member::with('memberSource')->get();
return Datatables::of($members)
->addColumn('source_of_member', function ($member) {
$member_name = '';
if(!empty($member->memberSource->name)){
$member_name = $member->memberSource->name;
}
return $member_name;
})
->addColumn('action', function($member){
return '<a data-id="'.$member->id.'" href="#" data-toggle="modal" id="openShow" class="btn btn-info btn-xs"><i class="fas fa-eye"></i></a> ' .
'<a href="member/edit/'.$member->id.'" class="btn btn-primary btn-xs"><i class="fas fa-edit"></i></a> ' .
'<a href="member/delete/'.$member->id.'" class="btn btn-danger btn-xs"><i class="fas fa-trash-alt"></i></a>';
})
->make(true);
答案 1 :(得分:1)
在关系正常运行的情况下,您只需编辑数据表中的列即可:
$members = Member::with('memberSource');
return Datatables::of($members)
->editColumn('source_of_member', function ($member) {
return $member->memberSource->name;
})
->addColumn('action', function($member){
return '<a data-id="'.$member->id.'" href="#" data-toggle="modal" id="openShow" class="btn btn-info btn-xs"><i class="fas fa-eye"></i></a> ' .
'<a href="member/edit/'.$member->id.'" class="btn btn-primary btn-xs"><i class="fas fa-edit"></i></a> ' .
'<a href="member/delete/'.$member->id.'" class="btn btn-danger btn-xs"><i class="fas fa-trash-alt"></i></a>';
})
->make(true);
但是,您的关系配置似乎有误,因为您的外键称为source_of_member
,因此laravel无法自动检测到它。
在您的Member
模型中:
public function memberSource()
{
return $this->hasOne('App\MemberSource', 'source_of_member');
}
在您的MemberSource
模型中:
public function member()
{
return $this->belongsTo('App\Member', 'source_of_member');
}