[英]How to query pivot table using Eloquent in Laravel 5
我的客户表和标签表之间存在多对多关系。 一个客户端可以具有多个标签,并且每个标签可以与多个客户端相关。
在客户端显示视图上,我试图显示客户端信息以及与此客户端关联的所有标签。
如何更改下面的查询以检索具有所有相关标签的客户行?
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();
});
}
您可以使用如下的“快速加载”方法
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.