【问题标题】:How to query pivot table using Eloquent in Laravel 5如何在 Laravel 5 中使用 Eloquent 查询数据透视表
【发布时间】:2015-12-28 13:41:13
【问题描述】:

我的客户表和标签表之间存在多对多关系。一个客户端可以有多个标签,每个标签可以关联多个客户端。

在客户端显示视图中,我正在尝试显示客户端信息以及与此客户端关联的所有标签。

如何更改下面的查询以检索客户端行及其所有相关标签?

public function show($id)
{
    $client = Client::findOrFail($id);

    return view('clients.show')->with(['client' => $client]);
}

客户端模型

public function clienttag()
{
    return $this->belongsToMany('App\Clienttag');
}

客户标签模型

public function client()
{
    return $this->belongsToMany('App\Client');
}

Client_clientags 表迁移

public function up()
{
    Schema::create('client_clienttag', function(Blueprint $table)
    {
        $table->integer('client_id')->unsigned();
        $table->foreign('client_id')->references('id')->on('clients')->onDelete('cascade');

        $table->integer('clienttag_id')->unsigned();
        $table->foreign('clienttag_id')->references('id')->on('clienttags')->onDelete('cascade');

        $table->timestamps();
    });
}   

客户表迁移

public function up()
{
    Schema::create('clients', function(Blueprint $table)
    {
        $table->increments('id');

        $table->string('first_name');
        $table->string('last_name');

        $table->rememberToken();
        $table->timestamps();
    });
}

Clienttags 表迁移

public function up()
{
    Schema::create('clienttags', function(Blueprint $table)
    {
        $table->increments('id');

        $table->string('tag');
        $table->text('description');

        $table->rememberToken();
        $table->timestamps();
    });
}

【问题讨论】:

    标签: php laravel laravel-5 eloquent


    【解决方案1】:

    您可以使用如下“急切加载”方法

    public function show($id)
    {
    $client = Client::with('clienttag')->findOrFail($id);
    
    return view('clients.show')->with(['client' => $client]);
    }
    

    http://laravel.com/docs/5.1/eloquent-relationships#eager-loading查看文档

    然后在您的视图中,您可以打印您的标签

     @foreach ($client->clienttag as $tag)
      {!! $tag->tagname!!} (or whatever your field in clienttags table name is)
     @endforeach
    

    【讨论】:

      猜你喜欢
      • 2018-11-11
      • 2015-06-24
      • 2017-05-05
      • 2015-09-30
      • 2016-02-06
      • 1970-01-01
      • 1970-01-01
      • 2018-12-08
      相关资源
      最近更新 更多