我正在使用 Eloquent 在 Laravel 8 中撰寫查詢。主題和流之間存在多對多的關系,它們的資料透視表是課程。
科目:身份證姓名
流 id 名稱
課程 ID subject_id stream_id
我必須獲取具有特定流的主題。
我寫了以下查詢。
$this->subjects = Subject::has('streams',$this->stream)->get();
我在這方面有問題。
課程表:
| ID | stream_id | 主題ID |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 1 | 3 |
| 4 | 1 | 4 |
| 5 | 2 | 1 |
| 6 | 2 | 2 |
| 7 | 3 | 1 |
這是樣本資料。如果我想獲取流 id 為 1 的主題,那么它只會獲取 id 為 3 和 4 的主題,而不是獲取 id 為 1 和 2 的主題。誰能解釋我為什么要跳過主題 id 為 1 和 2 的主題?
請任何人都可以幫助我。先感謝您 。:)
已編輯
class Subject
{
public function streams()
{
return $this->belongsToMany(Stream::class, 'courses',
'subject_id', 'stream_id');
}
}
class Stream
{
public function subjects()
{
return $this->belongsToMany(Subject::class, 'courses',
'stream_id', 'subject_id');
}
}
uj5u.com熱心網友回復:
要獲取具有特定相關模型的模型,您可以使用whereHas()方法。https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence
假設這$this->stream是一個Stream模型,您可以使用閉包whereHas方法:
$stream = $this->stream;
$this->subjects = Subject::whereHas('streams', function($query) use ($stream){
$query->where('streams.id', $stream->id);
})->get();
編輯:因為 $this->stream 是id你應該做的
$stream = $this->stream;
$this->subjects = Subject::whereHas('streams', function($query) use ($stream){
$query->where('streams.id', $stream);
})->get();
uj5u.com熱心網友回復:
您應該指定參考 id 的表名以避免歧義。
$this->subjects = Subject::whereHas('streams', function($query) use ($stream){
$query->where('stream.id', $stream->id);
})->get();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/422359.html
標籤:
