首页 文章

Laravel类别模型关系

提问于
浏览
1

我的数据库中有以下表结构 .

Table Name: tiles

列:id,tile_name,tile_thumb,tile_snippet

Table Name: tags

列:id,tag_title

Table Name: tile_tags

列:id,tile_id,tag_id

Models: Tile,Tag,TileTag

在我的主要模型类中,我指定了一个名为TileTag的模型的关系,它是一个数据透视表 .

<?php namespace Tiles;

use Illuminate\Database\Eloquent\Model;

class Tile extends Model {

    protected $table = 'tiles';


   public function tags() {

        return $this->belongsTo('Tiles\TileTag');

    }
}

在我的foreach循环中,它返回tile_name和我的表中的任何其他列,除了由relatipnship加入的列 .

@foreach($tiles as $tile)       
        <a href="tile/{{$tile->tile_name}}">
            <li class="col-md-4 mix" data-category="{{ $tile->tags->tag_title }}">
                {!! HTML::image($tile->tile_thumb, null, array('class' => 'img-responsive')) !!}
            </li>
        </a>                
@endforeach

如何在每个循环中对我的主条目进行排序时,如何将我的类别/标签链接到我的主条目?

我尝试在循环期间通过{{$ tile-> tags-> tag_title}}返回数据,但它返回一个空字符串 .

Controller Method:

class TileController扩展Controller {

/**
 * Display a listing of tiles from the database.
 *
 * @return Response
 */

public function index() {

    // Get tile data from the model
    $tiles = \Tiles\Tile::all();

    return view('pages.index', compact('tiles'));

}

Returned Array:
enter image description here

1 回答

  • 2

    我认为你不必为Tile_Tag创建一个模型 . Laravel可以开箱即用地处理ManyToMany关系(我想这是关系的类型,因为你使用数据透视表) . 你的模型应该是

    class Tile extends Model {
    
    protected $table = 'tiles';
    
    
     public function tags() {
    
        return $this->belongsToMany('Tiles\Tag');
     }
    }
    

    class Tag extends Model {
    
    protected $table = 'tags';
    
    
     public function tiles() {
    
        return $this->belongsToMany('Tiles\Tile');
     }
    }
    

    Laravel将知道您有一个名为"tag_tile"的数据透视表,其列为"tag_id"和"tile_id" . 查看相关文档here

    然后你可以像这样迭代每个瓷砖的标签集合

    @foreach ($tiles as $tile)
             {!!$tile->tile_name!!} 
             @foreach ($tile->tag as $tag)
               {!!$tag->tag_title!!} 
             @endforeach
    @endforeach
    

    希望能帮助到你 .

相关问题