现在我有新闻类别,新闻和新闻图片表结构,如:
我希望列出如下列表:
我如何制作具有雄辩关系的列表(哪里有或有)?
PS:有时新闻有图像
答案 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