如何在Laravel 5中使用Eloquent查询数据透视表

时间:2015-09-30 16:54:29

标签: php laravel laravel-5 eloquent

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

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

如何更改下面的查询以检索包含所有相关标记的客户端行?

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

1 个答案:

答案 0 :(得分:0)

您可以使用" Eager Loading"方法如下

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