簡體   English   中英

Laravel 多關系數據獲取

[英]Laravel Multiple relationships data fetch

再會。 我在 laravel 有這個關系問題 我有三個模型

  1. 用戶
  2. State
  3. 學校

我在它們之間建立了以下關系

一個。 學校 - 用戶(一個用戶可以注冊許多學校)

在用戶 Model

public function schools(){
        return $this->belongsToMany('App\Models\School', 'school_user', 'user_id', 'school_id');
}

灣。 一個學校可以有很多用戶

在校 Model

public function users(){
        return $this->belongsToMany('App\Models\User', 'school_user', 'school_id', 'user_id');
}

c。 一個學校屬於一個state(即c一個狀態)

在校 Model

public function states(){
        return $this->belongsTo('App\Models\State');
}

d。 A state 有很多學校

在 State Model

public function schools(){
        return $this->hasMany('App\Models\School');
}

現在,我知道如何查詢具有直接關系的模型了。 例如,我可以獲取與學校關聯的用戶,反之亦然。 我還可以在 state 中找到學校。

我的問題如何在給定的 state 中獲取與學校關聯的所有用戶(使用查詢)? 假設我們只有 state 的名稱。

並且可能獲取用戶關聯的所有學校以及與學校關聯的日期(時間)?

這就是我所做的。 第二個查詢沒有給我答案

public function details(){
        
        //Get all schools associated with a state 
        $schools = State::with('schools')->where('id',1)->first();
        
         foreach($schools->schools as $data){
          //Get all users associated with the schools
          $users = School::with('users')->where('id',$data->id);
          dd($users);  
        }    
    }

除了這種方法可能不正確之外,我沒有得到任何答案。 有沒有可以解決這個問題的查詢或方法?

謝謝。

使用whereHas可以獲取屬於具有給定state_id的學校的所有用戶。

$state = State::find(1);

$users = User::whereHas('schools', function ($query) use ($state) {
    $query->where('state_id', $state->id);
})->get();

查詢關系存在

如果您需要更多功能,您可以使用whereHasorWhereHas方法在您的has查詢上定義額外的查詢約束,例如檢查評論的內容:

use Illuminate\Database\Eloquent\Builder;

// Retrieve posts with at least one comment containing words like code%...
$posts = Post::whereHas('comments', function (Builder $query) {
    $query->where('content', 'like', 'code%');
})->get();

// Retrieve posts with at least ten comments containing words like code%...
$posts = Post::whereHas('comments', function (Builder $query) {
    $query->where('content', 'like', 'code%');
}, '>=', 10)->get();

您應該在關系數組屬性中看到相關模型

$school= App\Models\School::with('User', 'State')->get();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM