3 回答

TA贡献1810条经验 获得超5个赞
您可以在关系上使用查询构建器,如下所示:
$product->categories->orderBy('id', 'desc')->first();
这将从最近到最旧排序,您可以只获取第一条记录。

TA贡献1828条经验 获得超3个赞
在您的模型上使用特定方法
你的类别定义应该是这样的,对吧?
public function categories() {
return $this->belongsToMany(Category::class);
}
所以,只需创建另一种方法来检索最新的。
public function latestCategory() {
return $this->categories()->latest();
}
如果您需要最旧的类别,则应用相同的方法。
public function oldestCategory() {
return $this->categories()->oldest();
}
仅使用类别关系定义
如果您不打算创建新方法,也可以应用不同的方法:
$this->categories()->latest();
或者
$this->categories()->oldest();
希望它会帮助你。祝你有美好的一天。

TA贡献1790条经验 获得超9个赞
你可以使用latest()
方法
$product->categories->latest()->first();
或者,
$product->categories->orderBy('id', 'desc')->first();
- 3 回答
- 0 关注
- 198 浏览
添加回答
举报