Last active
December 26, 2015 18:49
-
-
Save ndamnjanovic/7197582 to your computer and use it in GitHub Desktop.
Laravel 4 - Eager loading
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Assume we have a following situation: | |
- We have a task that has associated checklists (one or many). | |
- Every checklist has associated items (again, one or many). | |
In Laravel 4, we can use Eager Loading to fetch all associated data. | |
Let's take a look. | |
First, we have have a TaskChecklistItem model as following: | |
// nothing special, regular Eloquent model | |
class TaskChecklistItem extends Eloquent{ | |
protected $table = 'taskchecklistitems'; | |
/** | |
* Mass fillable fields | |
* | |
* @var array | |
*/ | |
protected $fillable = array('description', 'task_checklist_id', 'is_done', 'order'); | |
} | |
Next, we'll have TaskChecklist model, that has defined relationship to checklist items. Something like this: | |
class TaskChecklist extends Eloquent{ | |
protected $table = 'taskchecklists'; | |
/** | |
* Mass fillable fields | |
* | |
* @var array | |
*/ | |
protected $fillable = array('title', 'task_id'); | |
public function items(){ | |
return $this->hasMany('TaskChecklistItem'); | |
} | |
} | |
In the end, we have Task model defined like this: | |
class Task extends Eloquent { | |
/** | |
* Mass fillable fields | |
* | |
* @var array | |
*/ | |
protected $fillable = array('title', 'description', 'order', 'points_id', 'user_id', 'board_id', | |
'status_id', 'priority_id', 'type_id', 'sprint_id', 'done_at', | |
'doer_id', 'parent_id'); | |
public function checklists(){ | |
return $this->hasMany('TaskChecklist'); | |
} | |
} | |
Now, when we're fetching data for task, and want to fetch all related checklists and their items, we can do it like this: | |
Task::with(array('checklists', 'checklists.items'))->where('tasks.id', $taskId)->get(); | |
and it will fetch all data that we need. As simple as that. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment