简体   繁体   中英

Laravel 4 - SQL query to Laravel Eloquent query

I'm working on a school project and I'm trying to get a query working.

SELECT *
FROM `ziekmeldingen` AS a
WHERE NOT EXISTS
    (SELECT *
     FROM `ziekmeldingen` AS b
     WHERE `ziek` = 1
       AND a.personell_id = b.personell_id)

Name of the model: ZiekmeldingenModel

I tried 2 things, both dont work ->

$medewerkers = ZiekmeldingenModel::whereNotExists(function($query)
        {
            $query->select()->from('ziekmeldingen AS b')->where('ziek', '=', '1')->where('ziekmeldingen.personell_id', '=', 'b.personell_id');
        })->get();
    return $medewerkers;

And

$medewerkers = ZiekmeldingenModel::raw('SELECT * FROM `ziekmeldingen` as a WHERE NOT EXISTS ( SELECT * FROM `ziekmeldingen` as b WHERE `ziek` = 1 AND a.personell_id = b.personell_id)')->get();

Both of them give back all the results from the table while it should only give back 1 result (I've tested the original query, it works).

EDIT: Forgot to mention I'm using relationships in the model. So the raw solution probably won't work anyway

Found the answer. Had to use a combo of both the things I tried.

$medewerkers = ZiekmeldingenModel::select()
                    ->from(DB::raw('`ziekmeldingen` AS a'))
                    ->whereNotExists(function($query){
                          $query->select()
                          ->from(DB::raw('`ziekmeldingen` AS b'))
                          ->whereRaw('`ziek` = 1 AND a.personell_id = b.personell_id');
                    })->get();

return $medewerkers;

Thanks for any help and effort.

Definitely no need for select() . Also no raw in from or whereRaw needed.

The only unusual thing here is raw piece in the where, since you don't want table.field to be bound and treated as string. Also, you can use whereRaw for the whole clause in case you have your tables prefixed, otherwise you would end up with something like DB_PREFIX_a.personell_id , so obviously wrong.

This is how you do it:

$medewerkers = ZiekmeldingenModel::from('ziekmeldingen AS a')
  ->whereNotExists(function ($q) {
     $q->from('ziekmeldingen AS b')
       ->where('ziek', 1)
       ->where('a.personell_id', DB::raw('b.personell_id'))
       // or:
       // ->whereRaw('a.personell_id = b.personell_id');
  })->get();

使用take()方法,但是,如果不对结果进行排序,则返回的记录可能是任何结果。

$medewerkers = ZiekmeldingenModel::raw('SELECT * FROM `ziekmeldingen` as a WHERE NOT EXISTS ( SELECT * FROM `ziekmeldingen` as b WHERE `ziek` = 1 AND a.personell_id = b.personell_id)')->take(1)->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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