2015-09-30 101 views
0

我的客戶端和標籤表之間有多對多的關係。客戶端可以有很多標籤,每個標籤可以與多個客戶端相關聯。如何在Laravel中使用Eloquent查詢數據透視表5

在客戶端顯示視圖中,我試圖顯示客戶端信息以及與此客戶端關聯的所有標記。

如何更改下面的查詢以檢索具有所有相關標籤的客戶端行?

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

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

客戶端模型

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

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

回答

0

您可以使用 「預先加載」 像下面

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 
+0

它就像一個魅力!謝謝@geoandri – user3489502

相關問題