How can I query raw via Eloquent?

前端 未结 8 1222
眼角桃花
眼角桃花 2020-12-02 20:42

I am trying to do a query in my Laravel app and I want to use a normal structure for my query. This class either does use Eloquent so I need to find something to do a query

8条回答
  •  渐次进展
    2020-12-02 20:57

    Old question, already answered, I know.

    However, nobody seems to mention the Expression class.

    Granted, this might not fix your problem because your question leaves it ambiguous as to where in the SQL the Raw condition needs to be included (is it in the SELECT statement or in the WHERE statement?). However, this piece of information you might find useful regardless.

    Include the following class in your Model file:

    use Illuminate\Database\Query\Expression;
    

    Then inside the Model class define a new variable

    protected $select_cols = [
        'id', 'name', 'foo', 'bar',
        Expression ('(select count(1) from sub_table where sub_table.x = top_table.x) as my_raw_col'), 'blah'
    ]
    

    And add a scope:

    public function scopeMyFind ($builder, $id) {
        return parent::find ($id, $this->select_cols);
    }
    

    Then from your controller or logic-file, you simply call:

    $rec = MyModel::myFind(1);
    dd ($rec->id, $rec->blah, $rec->my_raw_col);
    

    Happy days.

    (Works in Laravel framework 5.5)

提交回复
热议问题