I have a method where I store Collection
s into a Collection
. The Problem is that I get a multidimensional Collection
and I need a one-dimensional Collection
so I can use the available methods for Collection
s in Laravel.
I tried it with a loop to convert my multidimensional Collection
and it works fine, but I look for way to make it a little bit cleaner.
Thanks for help and hints.
$activities = new Collection();
$last = new Collection();
foreach ($this->members()->get() as $member)
{
$memberActivity = Activity::where('user_id', $member->id)->get();
$activities->add($memberActivity);
}
foreach($activities as $activity)
{
foreach($activity as $result)
{
$last->add($result);
}
}
$result = $result->sortBy('created_at');
return $result->last();
Not sure what you are trying to achieve for certain, but this looks like a many-to-many relationship.
From your question, You appear to have 3 tables members
, activities
and member_activities
with member_activities
being your pivot table.
So you should have 2 eloquent Models: Member
and Activity
. See http://laravel.com/docs/5.1/eloquent-relationships#many-to-many
class Member extends Model
{
public function activities()
{
return $this->belongsToMany(Activity::class, 'member_activities');
}
}
class Activity extends Model
{
public function members()
{
return $this->belongsToMany(Member::class, 'member_activities');
}
}
So you can access a members activities by doing something like the following:
$memberWithActivities = Member::with('activities')->find($memberId);
or
$member = Member::all();
foreach ($member->activities as $activity) {
//
}
or
$activities = Member::find($memberId)->activities()->orderBy('name')->get();
If you want to add an activity to a member, you can attach
and detach
- see http://laravel.com/docs/5.1/eloquent-relationships#inserting-many-to-many-relationships
nb - I've not checked my syntax, but the concept still applies.
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.