Laravel返回兄弟姐妹导致非对象情况

时间:2018-02-14 01:38:59

标签: php laravel-5 eloquent

我有一个导入数据库的用户表。我保留他们原来的id作为reference_id:

id    |  reference_id   |   parent_id
1           35                null
2           36                 35
3           37                 35
4           38                null
5           37                 38

我想回到整个家庭。在laravel我在模型中使用它:

public function getFamily(){
    $parent = User::where('user_id', auth()->id())
    ->where('parent_id', $this->parent_id)->get();

    $children = User::where('user_id', auth()->id())
    ->where('reference_id', $this->parent_id)->get();

    return $parent->merge($children);
}

然后在刀片模板中调用它:

$family= $tasks->user->getFamily();

foreach($family as $member){
    print_r($member->appointments->some_field);
}

当我执行print_r我试图调用非对象时出现错误,我不知道该怎么做。约会是指另一个模型/表。

在用户模型的其余部分中,我能够通过以下方式更简单地完成:

public function getFamily(){
    return $this->hasMany('App\Models\User', 'reference_id', 'parent_id');
        ->where('user_id', auth()->id())
        ->where('parent_id', $this->parent_id);
}

这个特别的"应该"在这样调用时返回了所有的兄弟姐妹:$family= $tasks->user->getFamily然后我可以访问约会模型,但是我收到一个错误,我的内存耗尽试图使用大约1.6Gb:

[2018-02-14 00:25:15] local.ERROR: Symfony\Component\Debug\Exception\FatalErrorException: Allowed memory size of 2634022912 bytes exhausted (tried to allocate 1608531968 bytes) in /var/www/html/laravel/storage/framework/views/bcfe7a474602582174256aacc1597a287fcb4e5e.php:213

有没有办法调整我的第一个和正在运行的函数,还允许我加入相关的表?除此之外,第二个查询中是否有一些我不知道的东西?

1 个答案:

答案 0 :(得分:0)

首先,我要将getFamily功能更改为local scope

public function scopeFamily ($query) {
    return $query->where('id', auth()->id())->where(function ($query) {
        $query->where('parent_id', $this->parent_id)
              ->orWhere('reference_id', $this->parent_id);
    });
}

然后,您应该可以通过以下方式访问所有Appointment模型:

$appointments = User::family()->each->appointments;

修改

public function scopeFamily($query, $parentId) {
    if(isset($parentId)){
        return $query->where('user_id', auth()->id())->where(function ($query) use ($parentId) {
            $query->where('parent_id', $parentId)
                  ->orWhere('reference_id', $parentId);
        });
    }
}