belongsTo 关系没有正常工作?

belongsTo relationship not working as it should?

我的模型中有这个关系:

class Product extends Model
{
    protected $fillable = [
        'id', 'title', 'description', 'main_image', 'price', 'category_id', 'in_stock', 'ammount', 'status', 'quatable', 'images'
    ];

    public function enabled_category()
    {
        return $this->belongsTo('App\Categories', 'category_id')->where('enabled', 'yes');
    }

}

我正在尝试获取属于已启用类别的产品,其中已启用 == 是

所以我是这样得到它们的:

$products = Product::with('enabled_category')->get();

但我仍然得到禁用类别的产品,其中 categories.enabled == 'no'

在我的 phpdebugbar 中,我只看到调用了这 2 个查询:

select * from `products`


select * from `categories` where `enabled` = 'yes' and `categories`.`id` in ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49')

而且我仍然得到所有的产品,即使是那些有残疾类别的产品。

为什么会这样,我如何才能获得仅属于已启用类别的产品?

它完全按照您的要求做...

$products = Product::with('enabled_category')->get();

您基本上是在告诉 Eloquent、获取所有产品并为这些产品预加载 enabled_category 关系。因此它将加载所有产品

select * from `products`

然后预先加载这些产品的关系(in 列表是要为其加载关系的产品 ID,注意你的 where 子句包含在其中,所以不要预先加载 enabled=no,因为它应该...那里的优化很好,只有 2 个查询...)

select * from `categories` where `enabled` = 'yes' and `categories`.`id` in ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49')

@NetGuy 建议轻松逆转查询...这正是您要找的。

Category::where("enabled", "yes")->with("products")->get();

您只需在类别中定义产品关系...

希望对您有所帮助

根据 Eloquent: Relationships 中的文档,您正在尝试直接在动态属性中查询结果。尝试这样做:

在你的模型中

public function enabled_category() {return $this->belongsTo('App\Categories', 'category_id'); }

然后在你的控制器中

Category::where("enabled", "yes")->with("products")->get();

应该可以!