簡體   English   中英

用於多個內部聯接的Laravel模型方法

[英]Laravel model approach for multiple inner join

我正在創建一個用於學生日程安排的應用程序。 在我的應用中,我只想獲取ID為1的學生時間表,並有其時間表詳細信息。

我有3個表:Student_Schedules,Schedule,Schedule_details

表格如下所示:

Student_Schedules :id,schedule_id

Schedule_details :id,schedule_id

時間表 :id

所以這是數據庫查詢:


$schedule = DB::table('Student_Schedules')
        ::join('schedules', 'Student_Schedules.schedule_id', '=', 'schedules.id')
        ->join('schedule_details', 'schedules.id', '=', 'schedule_details.schedule_id')
        ->where('Student_Schedules.id', '=', 1)
        ->get('Student_Schedules.*');

由於我不擅長laravel雄辯的關系。 是否可以使用帶有多個內部聯接的給定查詢的模型方法。 任何幫助表示贊賞:>

對您的答案是問題,是的,可以使用模型方法。 您的表將需要三個Eloquent模型。 它們是Schedule,StudentSchedule,ScheduleDetail。 您可以使用以下命令創建它:

php artisan make:model Schedule
php artisan make:model StudentSchedule
php artisan make:model ScheduleDetail

現在在Schedule.php文件中,創建與StudentSchedule,ScheduleDetail模型的關系

public function studentSchedule()
{
    return $this->hasMany(StudentSchedule::class, 'schedule_id');
}

public function scheduleDetail()
{
    return $this->hasOne(ScheduleDetail::class, 'schedule_id');
}

現在在StudentSchedule.php文件中創建其與Schedule模型的關系:

public function schedule()
{
    return $this->belongsTo(Schedule::class, 'schedule_id');
}

然后將查詢替換為:

StudentSchedule::with(['schedule' => function ($query) {
        $query->with('scheduleDetail');
    }])->where('id',1)->first();

這是一個鏈接 ,可以更好地理解laravel Eloquent模型關系。

希望對您有幫助。

好吧,我已經閱讀了您的帖子。 使用laravel雄辯的關系非常重要,這是laravel的另一個功能,因此您可以在每個表或模塊中使用數據庫模型。答案如下:

  1. 遷移數據庫表。 制作每個模型時,都可以在它們之間建立關系。

例:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Student_Schedules extends Model
{
    /**
     * Get the phone record associated with the user.
     */
    public function Schedules()
    {
        return $this->hasOne('App\Schedules');
    }
}

上面的示例表示您不連接2個表並通過在Student_Schedules模型對象結果上使用功能Schedules使用時間表信息

2.然后可以使用他們的關系模型對象,

$schedule = Student_Schedules ::find(1)->Schedules;

更多信息,請聯系。 謝謝...

在幼蟲中,雄辯的關系在性能和准確性方面總是好的。 您還必須使用如下關系:

你有三張桌子

  1. 時間表
  2. 學生時間表-帶時間表的外鍵
  3. 時間表詳細信息-帶時間表的外鍵

我假設您有一個學生表,其ID放在學生時間表中-我們將擁有雄辯的關系,例如

1)時間表模型

public function studentSchedules(){
 return $this->hasMany(StudentSchedule::class,'schedule_id');
}

public function scheduleDetail(){
 return $this->hasMany(ScheduleDetails::class,'schedule_id');
}

現在您可以在邏輯中使用這些關系

$schedules = Schedule::all(); /** conditional data must be used always */
foreach($schedules as $key => $schedule){
 $schedules[$key]->details = $schedule->scheduleDetail;
 $schedules[$key]->studentDetail = $schedule->studentSchedules;
}

等等,您也可以使用其他關系。 Laravel關系具有更優化的查詢,因此我們必須首先喜歡laravel雄辯的關系。

希望對您有幫助

暫無
暫無

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

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