请考虑下表:
user
id
name
client
id
name
user_client
user_id
client_id
rate
...
我想让我的控制器获取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');
}
}
没有适用于user_client
的模型。
我的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'));
}
虽然运行得很好,但让我们来看一下视图users/show.blade.php
<h1>{{$user->name}}</h1>
@foreach($clients as $client)
<p>{{$client->name}}, {{$client->rate}}</p>
@endforeach
$client->rate
未定义。检查我的查询调试器,belongsToMany将只选择client.*
,但它不会选择user_id
和client_id
以外的任何内容。
如何修改User::find($user->id)->clients;
,使其也选择user_client.*
?
编辑:在此期间,也欢迎您提出任何改进建议。
发布于 2014-01-15 20:20:52
如果您引用laravel docs on pivot tables,则需要在您的关系中添加withPivot
。
在您的示例中,您需要添加以下内容:
class User extends Eloquent
{
public function clients()
{
return $this->belongsToMany('Client', 'user_client')->withPivot('rate');
}
}
更新视图,如下所示:
<h1>{{$user->name}}</h1>
@foreach($user->clients as $client)
<p>{{$client->name}}, {{$client->pivot->rate}}</p>
@endforeach
我也会急切地加载客户端,以节省您的时间:
public function show($username) // foo.com/user/{$username}
{
$user = User::with('clients')->where('username', '=', $username)->firstOrFail();
return View::make('users.show', compact('user'));
}
希望这能有所帮助:)
https://stackoverflow.com/questions/21141039
复制相似问题