我要提出请假申请,老板可以在其中接受或拒绝请假请求
我在数据库中的表是这样的
id | name | email | person_in_charge |
1 Michael michael.com 2
2 Johan johan.com 4
3 Lorem lorem.com 2
4 Ipsum ipsum.com 5
5 Dolor dolor.com
我想,如果用户ID为5,则他可以查看所有请求。如果用户ID 2登录,则他可以查看用户ID 1和3的请假请求。如果用户ID 4登录,则可以查看用户ID 2,用户ID 1和用户ID 3的请假请求。
我正在使用while循环,但是出现错误消息“试图获取非对象的属性”
这是代码
$id='5';
$query= Users::where('id',$id)->first();
if($query->pic_for==null)
{
$query = Users::where('pic_for',$id)->first();
$pic_for = $query->id;
$pic=array($query->id);
while($pic_for!=null)
{
$query2 = Users::where('pic_for',$pic_for)->first();
//dd($query2);
if($query2->pic_for==null)
{
break;
}else
{
$pic[]=$query2->id;
$pic_for = $query2->id;
}
}
dd($pic);
}
你知道我想念哪里吗?
谢谢
答案 0 :(得分:1)
我会尝试的:
// prepare an empty $result collection that will store the ids of the users
$result = collect();
// probably a number, not a string, in your database: we should keep the right type
$id = 5;
addRelatedUsersToResult($id, &$result);
dd($result);
// add all the related users ids to the result
// and call itself for each realted user (to check their relations)
function addRelatedUsersToResult($id, &$result) {
$relatedUsers = Users::where('pic_for', $id)->get();
// add the related users and checks their children
foreach ($relatedUsers as $relatedUser) {
$result->push($relatedUser->id);
addRelatedUsersToResult($relatedUser->id, $result);
}
}
答案 1 :(得分:0)
尝试一下:
$user = Users::find(5); //get the inital user
$picFor = $user->pic_for; //get its pointer
$pictures = []; //initialize the result array
while (!is_null($user) && !is_null($picFor)) { //if I have a valid user and pointer
$user = Users::find($picFor); //get the user for the pointer
if ($user !== null) { //if I have a valid user
$picFor = $user->pic_for; //get the next pointer
$pictures[]= $user->id; //add the user id to the result array
}
}
您遇到的主要问题是缺少一些空检查。