2016-05-18 4 views
0

私は私の刃でこのコードスニペットがあります:$製品 - >タグでブレード内のリレーションからのデータへのアクセス? - Laravel

@foreach($products as $product) 
    <tr> 
     <td></td> 
     <td>{{ $product->name }}</td> 
     <td>{{$product->tags}}</td> 
     <td>{{$product->created_at}}</td> 
     <td> 
      // some other code and buttons 
     </td> 
    </tr> 
@endforeach 

を(タグは私のリレーションの名前です)、私は必要なタグや他のいくつかのものですが、私は唯一のタグが必要です。

私は$ product-> tags->タグでそれらに到達しようとしましたが、これは私のためには機能しませんでした。タグだけにアクセスする方法を教えてもらえますか?

+0

を使用することができますがダミーの製品オブジェクトを投稿することができます... –

+0

は私の質問 – WellNo

+0

完全な製品オブジェクトをプリントアウトを更新しました、タグplz –

答えて

2

あなたProducts間に設定関係を持っており、それは、Tagshttps://laravel.com/docs/5.1/eloquent-relationships

製品モデル

//namespace and use statements 
class Products extends Model 
{ 
    /** 
    * Get all of the tags for the product. 
    */ 
    public function tags() 
    { 
     return $this->hasMany('App\Tags'); 
    } 
} 

タグモデル (と仮定すると、タグが複数の製品に使用することができます)

//namespace and use statements 
class Tags extends Model 
{ 
    /** 
     * The tags that belong to the product. 
     */ 
    public function products() 
    { 
     return $this->belongsToMany('App\Products'); 
    } 
} 
なら

次に、コントローラで、タグ付き製品を照会することができます(https://laravel.com/docs/5.1/eloquent-relationships#querying-relations

$products = App\Products::with('tags')->get(); 

その後、あなたは、単にあなたの現在のコードであなたのビューでそれらにアクセスするが、

@foreach($products as $product) 
    <tr> 
     <td></td> 
     <td>{{ $product->name }}</td> 
     @foreach($product->tags as $tag) 
      <td>{{ $tag->name }}</td> 
     @endforeach 
     <td>{{ $product->created_at }}</td> 
     <td> 
      // some other code and buttons 
     </td> 
    </tr> 
@endforeach 
+0

あなたのすべての仕事に感謝します:)完璧に働いた! – WellNo

3

はこれを試してみてください:

@foreach($product->tags as $tag) 
    <td>{{ $tag->tag }}</td> 
@endforeach 

$product->tagsreturnTagオブジェクトのarrayね。

関連する問題