在 Laravel 5.6 中使用 hasOne 检索数据

Retreive data with hasOne in Laravel 5.6

我想知道如何在laravel中使用hasOne检索数据? 例如,我有一个品牌 table 和一个产品 table,其中有一列包含品牌的 ID,因此如果一个产品应该有一个品牌 "hasOne",那么它与两个 tables,但是如果产品不一定有品牌,那么在添加产品时,数据库中存储的品牌 id 为 0,当我在此行发出请求时,laravel 给我一个错误。

感谢您的回答。

当产品没有品牌时,不加0,而是在数据库中输入NULL。 您将需要更改数据库并将 ->nullable() 添加到 brand_id

此外,Product 似乎应该 belongTo 一个 Brand 而不是 hasOne

您的 Product 模型应该如下所示:

class Product extends Model {

    public function brand() {
        return $this->belongsTo(Brand::class);
    }
}

还有你的Brand

class Brand extends Model {

    public function products() {
        return $this->hasMany(Product::class);
    }
}

那么您可以进行以下操作:

if($product->brand) {
    // product has brand
}
else {
    // product does not have brand
}