I've got for the first time in L4 the need to establish a many-to-many relationship. For what I understood, so far, I need three tables... I have the following:
users
- id
- username
- ...
platforms
- id
- title
- ...
users_platforms
- platform_id
- user_id
How can I now insert data into the users_platforms table? I have the User model and the Platform model. How should both these be related... and how the actual content is saved to the related table?
On hasMany relationships I would create a new user and then save it like $user->something()->save($something) but I naturally can't do something like that in here.
Thoughts?
Having a User model with your relation:
class User extends Eloquent {
public function platforms()
{
return $this->belongsToMany('Platform', 'users_platforms');
}
}
You just have to attach it:
$platform = new Platform;
$platform->name = 'OSX';
$platform->save();
$user = User::find(1);
$user->platforms()->attach($platform->id);
Related
Assume I have posts and videos that can be seen by multiple users.
- users
- id
- posts
- id
- videos
- id
- user_accessables (pivot)
- id
- user_id
- accessable_id
- accessable_type
In an example like that, I have set my User relationship like so but something feels wrong
class User extends Model {
public function posts() {
return $this->morphedByMany(
Post::class,
'accessable',
'user_accessables'
);
}
public function videos() {
return $this->morphedByMany(
Video::class,
'accessable',
'user_accessables'
);
}
public function allowedEntities() {
return ($this->posts)->merge($this->videos);
}
}
With the allowedEntities() I can get a collection of both models joined together.
However, I think the use of polymorphic relationship is returning a collection of entities through relationship rather than needing a combiner relationship, right?
I am having problems with understanding polymorphic with pivot table (the tag example in documentation doesn't seem like same scenario).
Because now I can't do:
$collection = collect(); // multiple models of Video & Post
$user->allowedEntities()->sync($collection);
As #Jonas Staudenmeir said is not possible to have a relationship that returns all related model, BUT you can define a method on the model that returns a query builder object with all entities you need (search with on the docs).
I have a question that I'm looking for its answer for a while.
Well, in my Laravel Project, I have a Model Disease which has a belongstoMany relationship with Recipe and User Models.
I'm looking to fetch from database all recipe rows that have same disease_id as the current logged user.
Is there any way to do so with Eloquent?
Thank you !
Make sure your User model has a diseases relation defined:
public function diseases()
{
return $this->hasMany(Disease::class);
}
You can get the current user and disease_id like this (edited to use the diseases relation on the Users model):
$user = Auth::user();
$disease_ids = $user->diseases()->pluck('id');
Then you can find the recipes with the same disease_id like this:
return Recipe::whereIn('disease_id', $disease_ids)->get();
Would something like this work:
$user = Auth::user();
return Recipe::where('disease_id', $user->id)->get();
I have gotten a model called User. in this model i have a function called UserActivity where i return this:
return $this->hasMany('App\UserActivity', 'userid');
After this i have a function that gets the activity name from the Activity table, but i do not know how to do this, i have currently gotten this:
public function Activity() {
return $this->hasManyThrough('App\UserActivity', 'App\Activity', 'userid', 'activityid');
}
And in my view i want to use this like this:
$activiteiten = \App\User::find(Auth::user()->id);
dd($activiteiten->UserActivity()->Activity());
But then i get an error saying this:
Call to undefined method Illuminate\Database\Query\Builder::Activity() (View: /var/www/vhosts/cpned.nl/intranet.cpned.nl/laravel/resources/views/dashboard.blade.php)
I can do it using inner joins but i am really wondering if i can do this with Laravel models. I do not know how currently, and because i don't know what the name is for the function in laravel i can't find it either, so I am sorry if this will be a duplicate.
My tables have the following keys and foreign keys:
Users: pk: id
user_activities: pk: userid, activityid
activities: pk: id
Thank you in advance!
You can try using eager loading.
So something like:
$activiteiten = \App\User::with('UserActivity.Activity')->find(Auth::user()->id);
dd($activiteiten->UserActivity->Activity);
Edit: So then you can do something like this:
foreach($activiteiten->UserActivity as $user_activity) {
foreach($user_activity->Activity as $activity) {
print_r($activity);
}
}
Shows how you can loop through the relationships.
The Activity function should be in the User model. So then you can call it this way:
$activiteiten = \App\User::find(Auth::user()->id);
dd($activiteiten->Activity); //gives you a collection of activities
However, you need belongsToMany function rather than hasManyThrough since the relationship between users and activities is many-to-many.
This mean you cut down going through the Intermediate model. You can check the doc on belongsToMany to understand what to do better.
A side note: Why are your functions name starting with capital letter?
Also using hasMany relations should affect the function name as well, so that 'activity' becomes 'activities' (just to keep the functionality and interpretation in sync).
Update:
//User model
public function activities() {
return $this->belongsToMany('App\Activity', 'user_activity', 'userid', 'activityid');
}
This uses the 'user_activity' table, to find the relationship between users and activities, so that you may now access by User::first()->activities for example.
I have 3 models: User, Campagin, CampaginType
User has many Campagin
Campagin belongs to CampaginType
(User does not related with CampaginType)
When I save a campaign (contains user_id and campaign_type_id field), how can I save 2 fields with a single command.
I try like:
$user->campaigns()->campaignType($campaignType)->create($campaignInfo);
But It not work! :(
public function store(Request $request)
{
Campaign::create($request->all());
$campaign = Campaign::where('unique_field', '=', $request->uniquefield)->first();
$campaign->users()->attach($request->user_id);
$campaign->campaign_type()->attach($request->campaign_type_id);
return redirect('your_destination_view');
}
Note
uniquefield is something that is unique to your campaign database table. You should also modify the models by adding the respective methods to make the eloquent relationship.
how can I choose which fields I want to get from the with ORM eloquent. For example
$tourTeams = Tournament::with('teams')->where('id', $tourId)->first();
From the teams relation I want only to get the name (without the id and timestamps).
I didn't it in the documentation. For the Tournament eloquent I can do it via the get function while passing it an array of fields names, like this: get(array('name', 'id')). But how do I do this on the Team eloquent?
Note: here is how Team related to Tournament, this code taken from the Tournament eloquent file:
public function teams()
{
return $this->belongsToMany('Team', 'Tournament_Team');
}
You can get specific columns from the relation like this:
$tourTeams = Tournament::with(['teams'=>function($q){
$q->select('id','name');
}])->where('id', $tourId)->first();