问题
I have a table of users that are imported to the DB. I keep their original id as reference_id:
id | reference_id | parent_id
1 35 null
2 36 35
3 37 35
4 38 null
5 37 38
I am trying to get back the entire family. In laravel I am using this in the model:
public function getFamily(){
$parent = User::where('user_id', auth()->id())
->where('parent_id', $this->parent_id)->get();
$children = User::where('user_id', auth()->id())
->where('reference_id', $this->parent_id)->get();
return $parent->merge($children);
}
and then in the blade template calling it like this:
$family= $tasks->user->getFamily();
foreach($family as $member){
print_r($member->appointments->some_field);
}
I am getting an error when I do the print_r
that I am trying to call on a non-object and I am not sure what to do about it. Appointments refers to another model / table.
In the rest of the User model I was able to do it more simply with something like this:
public function getFamily(){
return $this->hasMany('App\Models\User', 'reference_id', 'parent_id');
->where('user_id', auth()->id())
->where('parent_id', $this->parent_id);
}
This particular one "should" have returned all the siblings when called like this: $family= $tasks->user->getFamily
and then I could have accessed the Appointments Model, but I was getting an error that I was running out of memory trying to use about 1.6Gb:
[2018-02-14 00:25:15] local.ERROR: Symfony\Component\Debug\Exception\FatalErrorException: Allowed memory size of 2634022912 bytes exhausted (tried to allocate 1608531968 bytes) in /var/www/html/laravel/storage/framework/views/bcfe7a474602582174256aacc1597a287fcb4e5e.php:213
Is there any way to adapt my first and working function to also allow me to join on associated tables? Barring that, is there something obvious I am missing in the second query?
回答1:
I would start by changing the getFamily
function to a local scope.
public function scopeFamily ($query) {
return $query->where('id', auth()->id())->where(function ($query) {
$query->where('parent_id', $this->parent_id)
->orWhere('reference_id', $this->parent_id);
});
}
You should then have access to all Appointment
models via:
$appointments = User::family()->each->appointments;
edit
public function scopeFamily($query, $parentId) {
if(isset($parentId)){
return $query->where('user_id', auth()->id())->where(function ($query) use ($parentId) {
$query->where('parent_id', $parentId)
->orWhere('reference_id', $parentId);
});
}
}
来源:https://stackoverflow.com/questions/48778405/laravel-return-siblings-results-in-non-object-situation