php - How to query pivot table using Eloquent in Laravel 5 -
i have many-to-many relationship between client , tag tables. client can have many tags, , each tag can related multiple clients.
on client show view, i'm trying display client info plus tags associated client.
how change query below retrieve client rows 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
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
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 following
public function show($id) { $client = client::with('clienttag')->findorfail($id); return view('clients.show')->with(['client' => $client]); } check documentation @ http://laravel.com/docs/5.1/eloquent-relationships#eager-loading
then @ view can print tags
@foreach ($client->clienttag $tag) {!! $tag->tagname!!} (or whatever field in clienttags table name is) @endforeach
Comments
Post a Comment