简体   繁体   English

Laravel Eloquent 在同一个表中使用预加载查询同级

[英]Laravel Eloquent query siblings in same table with eager loading

I have a parent table called patients which has a one-to-many relationship with a child table called notes .我有一个名为patients的父表,它与一个名为notes的子表具有一对多的关系。 (ie One patient can have several notes). (即一个病人可以有几个笔记)。 If given a note, I would like to find other notes for the same patient.如果给出注释,我想为同一患者找到其他注释。 Notes are related to patients by a fk called patient_id .注释通过名为patient_id的 fk 与患者相关。

In SQL, I'd do this:在 SQL 中,我会这样做:

SELECT * FROM notes WHERE patient_id={note.patient_id} AND id <> {note.id}

In Eloquent, I have this:在 Eloquent 中,我有这个:

class Note extends Model
{

    public function otherEncounterNotes()
    {
        return $this->hasMany('App\Note', 'patient_id', 'patient_id')->where('id', '<>',$this->id);
    }
...

In my database, the patient with id=1 has two notes with ids 1 and 2, so if I look for the siblings of note id 1, I should get note id 2.在我的数据库中,id=1 的患者有两个 id 为 1 和 2 的笔记,所以如果我寻找笔记 id 1 的兄弟姐妹,我应该得到笔记 id 2。

When I use find() , it works as expected, but when I use where() , it returns the original note instead of the sibling.当我使用find()时,它按预期工作,但是当我使用where()时,它返回原始注释而不是兄弟。 Any ideas?有任何想法吗?

>>> Note::find(1)->otherEncounterNotes->pluck('id')                                                                                                                                                                             
=> Illuminate\Support\Collection {#5542
     all: [
       2,
     ],
   }

>>> Note::where('id',1)->with('otherEncounterNotes')->pluck('id')                                                                                                                                                               
=> Illuminate\Support\Collection {#5526
     all: [
       1,
     ],
   }

Given a Note id, you could obtain the results you want by using the relationship with the Patient model.给定一个Note id,您可以通过使用与Patient model 的关系来获得您想要的结果。

$note_id = 1;

// "Pretty" syntax, but it's 3 queries
$sibling_notes = Note::find($note_id)->patient->notes()->where('id', '<>', $note_id)->pluck('id');

Or using a subquery或使用子查询

$note_id = 1;

// A bit messier, 1 query + 1 subquery
$sibling_notes = Note::where('id', '<>', $note_id)
    ->where('patient_id', function ($subquery) use ($note_id) {
        $subquery->select('patient_id')->from('notes')->where('id', $note_id);
    })
    ->pluck('id');

// PHP >= 7.4
Note::where('id', '<>', $note_id)
    ->where('patient_id', fn($q) => $q->select('patient_id')->from('notes')->where('id', $note_id))
    ->pluck('id');

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

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