[英]Laravel Get 'belongsTo' relation from 'hasMany' relation
class Post {
function category() {
$this->belongsTo('Category');
}
}
class User {
function posts() {
$this->hasMany('Post');
}
function categories() {
//???
$this->posts->category;
}
}
我有看起來像這樣的代碼,我想知道如何訪問用戶對象上的“類別”並讓它返回 Laravel 關系。
現有的關系方法“hasManyThrough”等似乎都不適合這個用例。
也許你可以換個角度看? 從類別開始並按用戶過濾:
$userCategories = Category::whereHas('posts' function($query){
$query->where('user_id', $userId);
})->get();
這將抓取用戶發帖的所有類別。
另一種解決方案:
//user model
public function getCategoriesAttribute()
{
return $this->posts->lists('category')->unique();
}
要限制查詢,您可以更改帖子關系
//user model
function posts() {
$this->hasMany('Post')->with('category');
}
來源: http : //softonsofa.com/laravel-querying-any-level-far-relations-with-simple-trick/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.