【问题标题】:Left join with Where in Eloquent ORM在 Eloquent ORM 中左加入 Where
【发布时间】:2025-12-02 06:20:03
【问题描述】:

我正在尝试使用 Eloquent ORM 编写此 SQL 查询,但仍然没有成功:

SELECT *
FROM article

LEFT JOIN article_category
ON article.category_id = article_category.id

WHERE article_category.name_url = 'html'
LIMIT 10`

这是我目前想出的(我尝试只用一个查询来编写它,就像上面一样):

ArticleCategory::where('name_url', '=', 'html')->with('articles')->get();

但它显示错误:

Column not found:
1054 Unknown column 'article.article_category_id' in 'where clause'    
(SQL: select * from `article` where `article`.`article_category_id` in (1))

我的模型:

class Article extends Eloquent {

    protected $table = 'article';

    public function categories() {
         return $this->belongsTo('ArticleCategory', 'category_id');
    }
}

class ArticleCategory extends Eloquent {

    protected $table = 'article_category';

    public function articles() {
        return $this->hasMany('Article');
    }
}

【问题讨论】:

    标签: php mysql sql laravel eloquent


    【解决方案1】:

    您可以更改您的关系函数以使用正确的 ID。

    public function articles() {
        return $this->hasMany('Article', 'category_id');
    }
    

    【讨论】:

      【解决方案2】:

      它期望列 category_id 实际上被命名为 article_category_id。它期望这是因为它引用了表 artice_catigory,所以 article_category_id 是有意义的。

      如果可能,只需将表格 article 中的列重命名为 article_category_id,一切都会好起来的。

      【讨论】:

        【解决方案3】:

        您可以使用 eloquent orm 使用左连接,如下所示

        Article::leftJoin('article_category', 'article.category_id', '=', 'article_category.id')
                    ->select(['*'])->where('article_category.name_url','html')->take(10)->get();
        

        【讨论】: