Laravel:belongsToMany() 没有获取多对多表中的字段

标签 laravel many-to-many

考虑下表:

user
  id
  name

client
  id
  name

user_client
  user_id
  client_id
  rate
  ...

我希望我的 Controller 获取 user 表中的所有字段,并且之后我还想列出他们的客户 namerate。用户和客户端模型:

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'));
}

虽然运行良好,但让我们看一下 View users/show.blade.php:

<h1>{{$user->name}}</h1>
@foreach($clients as $client)
  <p>{{$client->name}}, {{$client->rate}}</p>
@endforeach

$client->rate 未定义。检查我的查询调试器,belongsToMany 只会选择 client.*,但不会选择 user_idclient_id 之外的任何内容。

如何修改 User::find($user->id)->clients; 以便它也选择 user_client.*

编辑:当我这样做时,也欢迎任何改进建议。

最佳答案

如果您引用laravel docs on pivot tables ,您需要在关系中添加 withPivot

在您的示例中,您需要添加以下内容:

class User extends Eloquent 
{

    public function clients()
    {
        return $this->belongsToMany('Client', 'user_client')->withPivot('rate');
    }
}

更新您的 View ,例如:

<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'));
}

希望有帮助:)

关于Laravel:belongsToMany() 没有获取多对多表中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21141039/

相关文章:

python - Django,使用 ManyToMany 将初始数据设置为 formset

cakephp - CakePHP 3.x 中的多对多关联

php - Algolia 为奴隶设置主索引

php - 如何在 Laravel 中使用一个查询来进行不同的选择?

mysql - Eloquent 如何处理 Relationship?

jpa - 使用 JPA 可以仅返回一列

php - 为 m :m relationship (pupil-evening_activity) consistently 插入行

php - 导入大型数据集的性能提示

php - 如果变量为空,Laravel Eloquent 地获得所有

symfony - Doctrine2 多对多多态关系