我正在 Controller 中获取记录:
$tasks = Task::where('user_id', '=', Auth::user()->id);
return view('todo',compact('tasks'));
但它返回 null。
并且 Auth::user()->id
返回 2
没问题。
我错过了什么吗?
最佳答案
您需要实际检索记录。您拥有的是 \Illuminate\Database\Eloquent\Builder
的实例,但不是与查询关联的实际记录。
要告诉 Eloquent 获取数据,您需要使用 get()
。
喜欢:
$tasks = Task::where('user_id', '=', Auth::user()->id)->get();
顺便说一句,您可以将查询简化为:
$tasks = Task::where('user_id', Auth::user()->id)->get();
此外,在您的 User
模型上,您可以执行以下操作:
public function tasks()
{
return $this->hasMany(Task::class) // make sure you use the full namespace here or use at the top of User.php
}
然后你可以简单地做:
$tasks = auth()->user()->tasks;
这是 Eloquent 中解释的关系 in the docs .
关于php - 拉拉维尔 5.2 : Fetch records against logged in user id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37084635/