【问题标题】:Laravel 5. Many-to-many relationsip. Build queryLaravel 5. 多对多关系。构建查询
【发布时间】:2015-12-02 08:54:03
【问题描述】:

表格:

categories
--id

materials
--id

category_material
--id
--category_id
--material_id

型号:

class Material extends Model {
    public function categories(){
        return $this->belongsToMany('App\Category');
    }
}

class Category extends Model {
    public function materials(){
        return $this->belongsToMany('App\Material');
    }
}

我需要“category_id = 1”中的所有材料

尝试:

$category_id = '1';
$materials = Material::with('categories')->where('category_id', $category_id)->get();

未知列“materials.category_id”

$category_id = '1';
$materials = Material::with(['categories',function($query) use ($category_id){
    $query->where('category_id', $category_id);
}])->get();

Builder.php 第 792 行中的错误异常: explode() 期望参数 2 是字符串,给定对象

请帮帮我。

【问题讨论】:

    标签: php laravel-5 eloquent many-to-many


    【解决方案1】:

    传递给with 的数组应为relation_name => closure 格式

    $category_id = '1';
    $materials = Material::whereHas('categories', function($query) use ($category_id){
        $query->where('category_id', $category_id);
    })->get();
    

    【讨论】:

    • 谢谢,但现在:SQLSTATE[23000]:完整性约束违规:1052 where 子句中的列 'category_id' 不明确
    • 将数据透视表名称添加到查询并尝试的位置。假设它是 category_material 在 where 查询 category_material.category_id 中像这样使用它。
    • 没有错误,但我得到了所有材料(我只需要来自“category_id = 1”)
    • 它的工作.. 我看了日志。为什么要这么难查询?我可以通过 Eloquent ORM 制作简单的“SELECT m.* FROM materials m LEFT JOIN category_material cm ON m.id = cm.material_id WHERE cm.category_id = 1”吗??
    猜你喜欢
    • 2016-10-06
    • 2019-04-24
    • 1970-01-01
    • 2018-11-02
    • 2015-05-29
    • 1970-01-01
    • 1970-01-01
    • 2020-12-15
    • 1970-01-01
    相关资源
    最近更新 更多