簡體   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