![](/img/trans.png)
[英]Laravel Property [title] does not exist on the Eloquent builder instance
[英]Laravel/Eloquent belongsToMany - Property [people] does not exist on the Eloquent builder instance
我想讓那些為雇主申請職位的人,因此我有很多對多的關系。
表..
applies -> | users_id(employee) | posts_id |
posts -> | id | user_id(employer) | (other posts cols ... )
user_info -> | id | (name col etc... for employee)
后 model
public function people()
{
return $this->belongsToMany(Info::class , 'applies', 'user_id' , 'posts_id');
}
Controller
public function index()
{
$user_id = Auth::id();
$myPosts = Post::where('user_id',$user_id)->get();
$employees = Post::where('user_id' , $user_id)->people; // this line
dd($employees);
}
如果我$employees = Post::find(//anyNumber//)->people;
效果很好但對於每個雇主 ID,它必須是動態的。
我試過這個$employees = Post::where('user_id', $user_id)->people;
但給出錯誤
Eloquent 構建器實例上不存在屬性 [people]。
find()
返回單個 model。 Post::where('user_id', $user_id)->people
仍然是一個 Eloquent Builder 實例。 您尚未完成查詢並獲得 model。 使用獲取 model 的方法( first()
, find()
等)應該可以解決問題。 像這樣:
employees = Post::where('user_id', $user_id)->first()->people;
我認為你想要做的是這樣的:
public function index()
{
$posts = Auth::user()->posts()->with('people');
return view("index")->with(["posts" => $posts]);
}
這將為您提供所有經過身份驗證的用戶的帖子並急切加載人員關系,因此在您的 Blade 模板中,您可以遍歷每個帖子並訪問與每個帖子關聯的人員:
<ul>
@foreach ($posts as $post)
<li>{{ $post->name }}</li>
<li>
<ul>
@foreach ($post->people as $person)
<li>{{ $person->name }}</li>
@endforeach
</ul>
</li>
@endforeach
</ul>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.