在为变量分配ID时,尝试在Laravel中获取非对象错误的属性
问题描述:
- I'm getting the row in the following code :
$grpusrow = DB::table('grpusrs')
->where('group_id', $id)
->where('user_id', $u_id)
->get();
- And then getting the ID in this line :
$grpusrid = $grpusrow->id;
- I receive the following error on the line in number 2 :
Trying to get property of non-object
答
->get() will always return multiple objects at once. You're simply not telling it which index of $grpusrow to get the ID from.
$grpusrows = DB::table('grpusrs')
->where('group_id', $id)
->where('user_id', $u_id)
->get();
foreach ($grpusrows as $grpusrow) {
dump($grpusrow->id);
}
// Or
$grpusrow = DB::table('grpusrs')
->where('group_id', $id)
->where('user_id', $u_id)
->first();
dump($grpusrow->id);
答
Maybe 2 solutions:
If you want a unique row in return (with a primary key in arguments for example), you should try ->first() instead of ->get().
The problem is the using of where clauses, I think it works with array when you want more than one where clause, try like this :
->where([['group_id', '=', $id],['user_id', '=', $u_id]])->get(); ( or first() )