繁体   English   中英

在两张桌子上雄辩的Laravel

[英]Eloquent on two tables Laravel

我有三个表:

-----------------
id | name | wheel
-----------------

-----------------------------
id |no_of_wheel | brand_wheel
-----------------------------

品牌_车轮

------------------------
id | brand_id | wheel_id
------------------------

我定义了以下模型:

class brand
{
    public function brandWheel(){
        return $this->hasMany(BrandWheel::class);
    }    
}

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

我想获得wheel_id为2的那些品牌。

我累了:

$brands = Brand::with(['brandWheel' => function($query){
    $query->where('wheel_id','=',2);
}])->get();

此代码为我提供了表格中所有的品牌。 我有什么想念的吗?

您的代码将获取所有品牌,并仅将wheel_id = 2的brandWheels附加到它们。您需要使用whereHas()方法。

$brands = Brand::with('brandWheel')
    ->whereHas('brandWheel', function($query){
        $query->where('wheel_id', 2)
    })
    ->get();

您应该使用whereHas语句。 with方法将渴望加载给定的关系。 您可以在此处找到更多文档。

$brands = Brand::with('brandWheel')->whereHas('brandWheel', function($query) {
    $query->where('wheel_id', 2);
})->get();

如果你只想要具有brandWheel关系使用的品牌has 有关更多信息,请查看文档

您需要使用此处描述的多对多口才关系https://laravel.com/docs/5.7/eloquent-relationships#many-to-many

因此,您的模型应如下所示:

class Brand 
{ 
    public function brandWheels()
    {
        return $this->belongsToMany(BrandWheel::class);
    }    
}

class BrandWheel
{
    public function brands()
    {
        return $this->belongsToMany(Brand::class);
    }
}

请注意,由于这是此处https://www.php-fig.org/psr/psr-1/#3-namespace-and-class-names定义的命名约定,因此我如何大写您的模型名称。

我还使您的关系名称复数,因为它们是多对多的,所以它们可以返回多个结果。

您现在可以按照以下方式做查询(未经测试,可能不是100%准确):

$brands = BrandWheel::find(2)->brands();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM