创建具有所需关系的模型

问题描述 投票:0回答:2

我正在尝试创建一个具有对象有效关系的模型。查询此模型不应返回任何缺少此关系的结果。似乎global scopes是这种情况的最佳选择,但是我一直无法做到这一点。难道我做错了什么?也许有更好的方法?

这是该模型的简化版本。

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Car extends Model
{
    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope('has_details', function ($builder) {
            $builder->has('details');
        });
    }

    public function details()
    {
        return $this->hasOne(Details::class);
    }
}

这是另一个模型上的一对多关系方法。

public function cars()
{
    return $this->hasMany(Car::class);
}

如果没有全局范围,此代码将返回所有相关的“汽车”,包括没有“详细信息”的汽车。在全球范围内,不会返回“汽车”。我希望这段代码只返回带有“细节”的“汽车”。

谢谢。

php laravel laravel-5 eloquent laravel-eloquent
2个回答
1
投票

您在Anonymous Global Scopes声明中有一些错误:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class Car extends Model
{
    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope('has_details', function (Builder $builder) {
           $builder->has('details');
        });
     }

    public function details()
    {
        return $this->hasOne(Details::class);
    }
}

0
投票

您可能会尝试急切加载关系,以便has()检查实际上会看到一些东西。 (我怀疑因为没有加载关系,所以从未填充过details关系。)

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class Car extends Model
{
    protected $with = ['details'];

    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope('has_details', function (Builder $builder) {
           $builder->has('details');
        });
     }

    public function details()
    {
        return $this->hasOne(Details::class);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.