简体   繁体   中英

Inner join in laravel using Eloquent

I have 2 model LeaveApplication and LeaveDetails model i would link to inner join leave with leaveDetails model

LeaveApplication Model

class LeaveApplication extends Model {

    public $table = 'leave_application';
    protected $fillable = ['user_id', 'start_date', 'end_date'];
    public function leaveDetails() {
        return $this->hasMany("App\LeaveDetails", 'application_id');
    }
}

This is LeaveDetails Model

class LeaveDetails extends Model {
    public $table = "leave_details";
    public $fillable = ['application_id','leave_date','leave_type'];
}

I try to access this using LeaveApplication::with('leaveDetails')->where('leaveDetails.leave_date','2016-10-10')->get()

It give me Error , This is not create inner join in eloquent.

I am also use whereHas('leaveDetails') and this not use inner join

LeaveApplication::with('leaveDetails')->where('leaveDetails.leave_date','2016-10-10')->get()

It won't work, because Laravel queries use few joins. If you work on eager loading, i suggest using constrained eager loading . Your Eloquent query will be looked like:

LeaveApplication::with(['leaveDetails' => function($query){
                                           $query->where('leave_date', '2016-10-10');
                                          }]);

If you're wondering what kind of query will be generated by Eloquent, try to dump it using toSql() .

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