我正在尝试从特定列中检索内容,下面是我尝试的内容
//get the department
$department = department::where('user_dep', '=', 1)->select('dep_id')->get();
//but seems the department retrieved an array, which I dont want, I want only the content
$notification = notification::where('department', '=', $department)->get();
但遗憾的是没有工作。似乎$department
检索了一个数组,比如列的标题及其我认为的值。
我尝试将$department
替换为特定的整数(1)并检索记录(它有效)但如果我使用$department
则返回空结果。有什么想法吗?
$notification = notification::where('department', '=', 1)->get();
$ department的vard_dump结果
object(Illuminate\Database\Eloquent\Collection)[206]
protected 'items' =>
array (size=1)
0 =>
object(App\department)[210]
protected 'table' => string 'department' (length=10)
protected 'connection' => null
protected 'primaryKey' => string 'id' (length=2)
protected 'perPage' => int 15
public 'incrementing' => boolean true
public 'timestamps' => boolean true
protected 'attributes' =>
array (size=1)
...
protected 'original' =>
array (size=1)
...
protected 'relations' =>
array (size=0)
...
protected 'hidden' =>
array (size=0)
...
protected 'visible' =>
array (size=0)
...
protected 'appends' =>
array (size=0)
...
protected 'fillable' =>
array (size=0)
...
protected 'guarded' =>
array (size=1)
...
protected 'dates' =>
array (size=0)
...
protected 'casts' =>
array (size=0)
...
protected 'touches' =>
array (size=0)
...
protected 'observables' =>
array (size=0)
...
protected 'with' =>
array (size=0)
...
protected 'morphClass' => null
public 'exists' => boolean true
答案 0 :(得分:1)
问题是由在Eloquent中使用错误的闭包方法引起的。使用->get()
将获取符合给定条件的所有行(即使您只查找单个行)并将其作为对象集合返回。使用->first()
将(逻辑上)找到第一个匹配的行并将其作为单个对象返回。有两种方法可以解决这个问题:
选项1:
$department = department::where('user_dep', '=', 1)->select('dep_id')->get();
$notification = notification::where('department', '=', $department[0]->dep_id)->get();
// var_dump($department); would equate to an array of `department` items;
返回整个集合,但只查找第一个结果' dep_id
。
选项2:
$department = department::where('user_dep', '=', 1)->select('dep_id')->first();
$notification = notification::where('department', '=', $department->dep_id)->get();
// var_dump($department); would equate to a single `department` item;
找到第一行并根据其dep_id
返回通知。两种方法都有效,但选项2将是更直接的选择。
答案 1 :(得分:0)
尝试使用它:
$department = department::where('user_dep', '=', 1)->select('dep_id')->get();
$notification = notification::where('department', '=', (int) $department)->get();