简体   繁体   English

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

[英]How to query pivot table using Eloquent in Laravel 5

I have a many-to-many relationship between my client and tag tables. 我的客户表和标签表之间存在多对多关系。 A client can have many tags, and each tag can be related to multiple clients. 一个客户端可以具有多个标签,并且每个标签可以与多个客户端相关。

On the client show view, I'm trying to display the client info plus all tags associated to this client. 在客户端显示视图上,我试图显示客户端信息以及与此客户端关联的所有标签。

How do I change the query below to retrieve the client rows with all its related tags? 如何更改下面的查询以检索具有所有相关标签的客户行?

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

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

Client model 客户模型

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

Clienttag model 客户标签模型

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

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

Clients table migration 客户表迁移

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 table migration Clienttags表迁移

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

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

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

You can use "Eager Loading" methods like the following 您可以使用如下的“快速加载”方法

public function show($id)
{
$client = Client::with('clienttag')->findOrFail($id);

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

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

Then at your view you can print your tags 然后,您可以查看自己的标签

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM