Laravel:belongsToMany() 不获取多对多表中的字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21141039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel: belongsToMany() does not get fields in the many-to-many table
提问by tiffanyhwang
Consider the following tables:
考虑以下表格:
user
id
name
client
id
name
user_client
user_id
client_id
rate
...
I want my controller to get all fields in the user
table and I also want to list their clients name
and rate
afterwards. User and Client models:
我希望我的控制器获取user
表中的所有字段,并且我还想列出他们的客户name
以及rate
之后的列表。用户和客户端模型:
class User extends Eloquent {
public function clients()
{
return $this->belongsToMany('Client', 'user_client');
}
}
class Client extends Eloquent {
public function users()
{
return $this->belongsToMany('User', 'user_client');
}
}
There is no model for user_client
.
没有模型user_client
。
An extract of my UsersController@show
我的摘录 UsersController@show
public function show($username) // foo.com/user/{$username}
{
$user = User::where('username', '=', $username)->firstOrFail();
$clients = User::find($user->id)->clients;
return View::make('users.show', compact('user', 'clients'));
}
While that runs fine, let's look at the view users/show.blade.php
:
虽然运行良好,但让我们看看视图users/show.blade.php
:
<h1>{{$user->name}}</h1>
@foreach($clients as $client)
<p>{{$client->name}}, {{$client->rate}}</p>
@endforeach
$client->rate
is undefined. Checking my query debuggers, belongsToMany will only select client.*
but it doesn't select anything other than user_id
and client_id
.
$client->rate
未定义。检查我的查询调试器,belongsToMany 只会选择client.*
但它不会选择除user_id
and以外的任何东西client_id
。
How can I modify User::find($user->id)->clients;
so that it will select user_client.*
as well?
我User::find($user->id)->clients;
该如何修改以便它也能选择user_client.*
?
EDIT: While I'm at it, any suggestions for improvements are also welcome.
编辑:虽然我在做,但也欢迎任何改进建议。
回答by Cristian
If you refer to the laravel docs on pivot tables, you will need to add withPivot
on your relationships.
如果您参考数据透视表上的laravel 文档,则需要添加withPivot
关系。
In your example you will need to add the following:
在您的示例中,您需要添加以下内容:
class User extends Eloquent
{
public function clients()
{
return $this->belongsToMany('Client', 'user_client')->withPivot('rate');
}
}
Update your view like:
更新您的视图,例如:
<h1>{{$user->name}}</h1>
@foreach($user->clients as $client)
<p>{{$client->name}}, {{$client->pivot->rate}}</p>
@endforeach
I would also eager load the clients to save you time:
我也很想加载客户端以节省您的时间:
public function show($username) // foo.com/user/{$username}
{
$user = User::with('clients')->where('username', '=', $username)->firstOrFail();
return View::make('users.show', compact('user'));
}
Hope that helps :)
希望有帮助:)