【发布时间】:2014-09-21 23:55:34
【问题描述】:
我有两张桌子:
items (
id
name
description
)
images (
id
item_id
number // 0 -> main image ; 1,2,3,4 ... -> gallery_image
)
有了这个基本关系:
#Item.php
public function images()
{
return $this->hasMany('Image');
}
和
#Image.php
public function item()
{
return $this->belongsTo('Item');
}
要在我的 index.php 中显示所有带有主图像的项目,我想获得 所有项目 和关系,但只有当“数字”等于“0”(主图像)时才具有关系。
如果使用:
$all = $this->item->get();
foreach ($all as $one) {
var_dump ($one->images);
}
然后我得到所有项目(完美)以及每个项目的所有图像。但我想要一个包含所有项目和每个项目一张图片的集合。
最好的方法是什么?
谢谢。
【问题讨论】:
-
这就是你需要的softonsofa.com/… - 在关系上使用
orderBy('number', 'asc') -
完美!感谢 public function main_image() { $this->hasOne('Image')->orderBy('number', 'asc')->latest(); }
-
接受答案以帮助面临同样问题的其他人。