Php 带约束的Laravel嵌套急加载
我有一个问题口才模型,一个课程口才模型,一个大学口才模型。大学与课程之间存在一对多的关系。问题与课程之间存在多对多关系。三种型号如下所示: 问题模型Php 带约束的Laravel嵌套急加载,php,laravel,eager-loading,Php,Laravel,Eager Loading,我有一个问题口才模型,一个课程口才模型,一个大学口才模型。大学与课程之间存在一对多的关系。问题与课程之间存在多对多关系。三种型号如下所示: 问题模型 namespace App; use Illuminate\Database\Eloquent\Model; class Question extends Model { /** * The database table that the Model uses * @var string */ prot
namespace App;
use Illuminate\Database\Eloquent\Model;
class Question extends Model
{
/**
* The database table that the Model uses
* @var string
*/
protected $table = "questions";
/**
* The fields that are mass assignable
* @var array
*/
protected $fillable = ['title','body','images','quality_score','deactivated','creator_id','reviewer_id'];
/**
* Images is stored as serialized json.
* So we cast it to a PHP array.
* See: http://laravel.com/docs/5.1/eloquent-mutators#attribute-casting
*/
protected $casts = [
'images' => 'array',
];
public function courses(){
return $this->belongsToMany('App\Course');
}
}
课程模式
namespace App;
use Illuminate\Database\Eloquent\Model;
class Course extends Model
{
/**
* The database table used by the model
* @var string
*/
protected $table = "courses";
/**
* The fields that can be mass assigned
* @var array
*/
protected $fillable = ['name', 'instructor', 'acronym', 'university_id', 'creator_id', 'reviewer_id'];
/**
* There exists a many to one relationship between the Course and User
* This user is the creator of the course
*
* @method void
*
*/
public function creator(){
return $this->hasOne('App\User','creator_id');
}
/**
* There exists a many to one relationship between the Course and User
* This user is the reviewer of the course
* The reviewer of the Course will always be an admin
* If an Admin is the creator, then the reviewer is also the same admin
*
* @method void
*/
public function reviewer(){
return $this->hasOne('App\User','reviewer_id');
}
/**
* There exists a one to many relationship between the University and the Course
* This university is where the course is held
* Courses may float i.e. not be associated to any university
*
* @method void
*/
public function university(){
return $this->belongsTo('App\University');
}
/**
* This method is an accessor. It automatically changes the acronym to be all capitals
* regardless of how it is stored in the database.
* See: http://laravel.com/docs/5.1/eloquent-mutators#accessors-and-mutators
* @param $value (String from Database)
* @return string (Capitalized String)
*/
public function getAcronymAttribute($value){
return strtoupper($value);
}
}
大学模式
namespace App;
use Illuminate\Database\Eloquent\Model;
class University extends Model
{
/**
* The database table used by the model
* @var string
*/
protected $table = "universities";
/**
* The fields that can be mass assigned
* name = Name of the University (Example: University of Illinois at Urbana Champaign)
* acronym = Acronym of the University (Example: UIUC)
* creator_id = Id of User that created the University
* reviewer_id = Id of User that reviewed and approved the University
*
* Universities will not be displayed to users without admin role unless they have been reviewed.
*
* @var array
*/
protected $fillable = ['name','acronym','creator_id','reviewer_id'];
/**
* This method is an accessor. It automatically changes the acronym to be all capitals
* regardless of how it is stored in the database.
* See: http://laravel.com/docs/5.1/eloquent-mutators#accessors-and-mutators
* @param $value (String from Database)
* @return string (Capitalized String)
*/
public function getAcronymAttribute($value){
return strtoupper($value);
}
}
在我的主页上,我显示了一个问题列表,并允许对课程和大学进行筛选。控制器方法如下所示:
public function getHome(Request $request){
/**
* Eager Load with Course and University
*/
$questions = Question::with('courses.university')->get();
/*
* Filter Questions to remove unwanted entries based on course id
*/
if($request->has('course_id') && $request->input('course_id') != -1){
$questions = $questions->filter(function($question) use ($request){
foreach($question->courses as $course){
if ($course->id == $request->input('course_id')){
return true;
}
}
});
}
/*
* Filter Questions to remove unwanted entries based on university id
*/
if($request->has('university_id') && $request->input('university_id') != -1){
$questions = $questions->filter(function($question) use ($request){
foreach($question->courses as $course){
if ($course->university->id == $request->input('university_id')){
return true;
}
}
});
}
/*
* Return the Welcome View with Pagination on the Questions Displayed
* List of Courses and List of Universities
*/
return view('welcome',[
'questions' => $questions,
'courses' => Course::all(),
'universities' => University::all(),
'selected_university_id' => $request->input('university_id',-1),
'selected_course_id' => $request->input('course_id',-1)
]);
}
我在上面所做的是从数据库返回所有问题,并对它们进行梳理,以删除所有与过滤器不匹配的问题。这显然是相当低效的。我想使用嵌套的即时加载约束,除非我在定义约束时遇到很多麻烦。此外,我希望使用服务器端分页,以使客户端在低速internet连接上的体验更好
以下是我的一个尝试:
$questions = Question::with(['courses.university' => function($query) use ($request){
if($request->has('university_id') && $request->input('university_id') != -1) {
$query->where('id', $request->input('university_id'));
}
if($request->has('course_id') && $request->input('course_id') != -1){
$query->where('courses.id',$request->input('course_id'));
}
}])->paginate(10);
当我没有任何过滤器时,这工作正常
当我确实定义了一个university_id时,我得到一个错误:试图获取非对象的属性(View:/var/www/testing.com/resources/views/welcome.blade.php)
当我确实定义了一个课程id时,我得到错误:SQLSTATE[42S22]:未找到列:“where子句”中的1054未知列“courses.id”(SQL:select*fromuniversities
whereuniversities
id
in(1,2)和courses
id
=1)
当我定义了course_id时,我预期会出现错误(因为我在$query->where方法的第一个参数处盲目尝试了一下)
我正在寻找有关定义嵌套的急切加载约束的帮助。我在一篇中型文章中找到了解决方案。该解决方案适用于laravel的更高版本,因为它使用了whereHas
// If you want to put the constraint on the second relation
$questions = Question::with(['courses' => function($query) use($request){
return $query->whereHas('university', function($inner_query) use($request){
return $inner_query->where('id', $request->input('university_id'));
});
}, 'courses.university'])->paginate(10);
就你的情况而言,一个简单的方法应该起作用
$questions = Question::whereHas('courses', function($query) use ($request){
return $query->where('university_id', $request->input('university_id'));
})->with(['courses.university'])->paginate(10);
我还建议使用when子句来减少代码量
$questions = Question::when(($request->has('course_id') && $request->input('course_id') != -1), function ($query) use($request){
return $query->where('course_id', $request->input('course_id'));
})->when($request->has('university_id') && $request->input('university_id') != -1, function ($outer_query) use($request){
return $outer_query->whereHas('courses', function($query) use($request){
return $query->where('university_id', $request->input('university_id'));
})->with(['courses.university']);
})->with(['courses.university'])->paginate(10);
您想要所选大学中的课程。如果需要,您可以完全从查询中删除大学。将其快速更改为
$query->where('id',$request->input('university_id');
到$query->where('university_id',$request->input('university_id');