jeudi 6 décembre 2018

Laravel 5.7 - accessor on a user model to get a collection's relationship based on a few factors

I have Users that could be related to items by a a few factors and I want to create a getItemDatesAttribute accessor that gets all of a users relevant items and get those items' dates. There isn't a direct relationship between the user and the dates in this scenario. I can get the relevant items:

/**
 * Accessor to get a user's relevant item dates
 *
 * @return mixed
 */
public function getItemDatesAttribute()
{
    $itemDates = Item::where('assigned_user_id', $this->id)
                   ->orWhereIn('assigned_team_id', $this->teams->pluck('id'))
                   ->with('dates')
                   ->get();
    dd($itemDates); // All the bugs with their dates if they have them...

    $itemDates->filter(function ($item) {
        // Not sure how to return just the dates
    });
}

Then I'm not really sure how to return all of the dates for all relevant bugs. The Item model has the relationship on it:

public function dates()
{
    return $this->hasMany(ItemDate::class, 'item_id', 'id');
}

The end result should be a collection of dates that through the few above factors (and any others needed) would be related to a user.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire