Laravel 5:如何在hasMany表上的字段中访问


Laravel 5 : how to acces in a field on the hasMany table?

我有两个模型与hasMany-to-many关系链接,并且有我的表结构

clients = id|title...etc
roles = id|title...etc
client_role = id|client_id|role_id|desc

一切都很好现在我想访问clientrole表上的desc字段,我该怎么做?我试过

$client =  Client::first()->roles()->desc 
//nothing returned!
$client =  Client::first()->desc 

但什么都没有!请帮助

您必须在模型关系中加载数据透视的列(例如,客户端):

return $this->belongsToMany('App'Role')->withPivot('desc');

然后你可以这样调用轴心中的列:

foreach ($clients as $client) {
    echo $client->pivot->desc;
}

在您的Clients模型中有:

public function roles() {
    return $this->belongsToMany('App'Clients');
}

在您的Roles型号中有:

public function clients() {
    return $this->belongsToMany('App'Roles');
}

然后从您的控制器:

$client =  Client::with('roles')->first();
dd($client->roles); // Laravel Collection