php - 在两张 table 上 Eloquent Laravel

标签 php mysql laravel eloquent

我有三个表:

品牌

-----------------
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();

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

最佳答案

您应该使用whereHas 语句。 with 方法将预先加载给定的关系。您可以找到更多文档 here .

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

如果您只想要具有 brandWheel 关系的品牌,请使用 has。结帐documentation有关更多信息。

关于php - 在两张 table 上 Eloquent Laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53427300/

相关文章:

php - 错误的结果 SoapVar

javascript - Jquery $.get() 操作 javascript 中查询产生的数据

PHP/mysql 获取数组中的多个变量

php - 使用查询生成器在 Laravel 中添加全文索引

php - 将 1 个数组的值合并到另一个键相同的数组

php - 仅显示多词变量中的第一个词

php session 超时

PHP MySql json 编码数组

java - 上传真实服务器上的opencms项目

php - Laravel Eloquent -- 表中的多条记录插入(具有唯一约束的列)