繁体   English   中英

左边加入Eloquent ORM中的Where

[英]Left join with Where in Eloquent ORM

我正在尝试用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');
    }
}

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

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

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

如果可能,只需将表格文章中的列重命名为article_category_id,一切都应该是好的。

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

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

暂无
暂无

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

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