建立多重雄辩的关系&有一个Where子句

时间:2014-05-22 06:43:49

标签: php mysql laravel eloquent

现在我有新闻类别,新闻和新闻图片表结构,如:enter image description here

我希望列出如下列表:enter image description here

我如何制作具有雄辩关系的列表(哪里有或有)?

PS:有时新闻有图像

1 个答案:

答案 0 :(得分:0)

假设您的模型名为Category并且有一个名为news的关系,并且还有一个名为image的关系,您只需执行以下操作即可。

$categories = Category::with(['news', 'news.image'])->all();

这会抓住所有类别的新闻和图像关系,如果他们有一个。

如果你没有设置关系,它看起来就像这样。

类别模型:

<?php
class Category extends Eloquent
{
    protected $table = 'category';

    public function news()
    {
        return $this->hasMany('News');
    }
}

新闻模式:

<?php
class News extends Eloquent
{
    protected $table = 'news_main';

    public function category()
    {
        return $this->belongsTo('Category');
    }

    public function image()
    {
        return $this->hasOne('NewsImage');
    }
}

新闻图片模型:

<?php
class NewsImage extends Eloquent
{
    protected $table = 'news_img';

    public function news()
    {
        return $this->belongsTo('News', 'id_news');
    }
}

注意

可能值得更改表格和某些字段的名称,以使命名结构更加统一和明智。

  • categories category_id
  • news news_id
  • news_images