using associate method in laravel - laravel

Assume we have one to many relationship like post and comment, each post hasMany comments and each comment belongsTo one post.
The question is how we could call associate method?
in Laravel document the associate method is called on relation method, something like:
$comment = new Comment(['title' => 'something']);
$post->comments()->associate($comment);
but in some cases, I saw the associate method is called on relation attribute like:
$comment = new Comment(['title' => 'something']);
$post->comments->associate($comment);
Are they the same? is there any difference between them?
Thanks

I don't think calling associate on a loaded relationship property works as it's either a database collection or a model (depends on the type of the relation). The method associate is only available on BelongsTo and MorphTo relationships.

Related

Eloquent - Multiple belongsTo?

I can't seem to find a straight answer on whether Eloquent models can have multiple belongsTo relationships.
Just in terms of normalized DB relationships, this is perfectly valid. Let's take the hypothetical example of a CMS page that belongs to one and only one author, and also belongs to one and only one category. The author and category have no relation to or bearing on one another. In the DB, we'd simply expect a page to have an author_id and a category_id field, each with a foreign key to a different table.
Seems like it would be valid to do:
class Page extends Model
{
public function author()
{
return $this->belongsTo(Author::class);
}
public function category()
{
return $this->belongsTo(Category::class);
}
}
The scenario seems valid ... EXCEPT that this seems to break the convention and automagic of the associate and dissociate methods, which expect there to be only a single "belongs to" relationship.
So is it proper to use multiple belongsTo relationships on the same model? And if not, how would you express a common scenario like this instead? (I should note right off the bat that this is not the same scenario as polymorphic relationships, where one model belongs to one other, which may be this OR that type.)
Eloquent Model's can have multiple same relationship. Means you can have belongsToMany() as many as you need, you can have a belongsTo(), hasOne(), hasMany() etc. It will not affect the other relationship since they have a different method name. which is the main identification for the relationship.
The scenario seems valid ... EXCEPT that this seems to break the convention and automagic of the associate and dissociate methods, which expect there to be only a single "belongs to" relationship.
If you understand the documentation Updating BelongsTo Relationship you will use the associate() or dissociate() after the relationship method. There's no "except there to be only a single belongs to relationship". in the documentation.
$page->author()->dissociate(); // it will set the "author_id" on the page as null and will not affect the `category()` at all.
$page->category()->associate($category); // it will add a the "category_id" of the given category to the page and will not affect the `author()` at all.

Laravel Relationships saving an array

I'm working on my first ever laravel project a crm. In my crm you can create appointments and packages. Now for the appointments I need to be able to select packages and set a relationship however I'm not sure I'm doing it correctly.
In my appointments model I have this in a function return $this->hasMany('App\Package');
and in my package model I have this in a function return $this->belongsTo('App\Appointment');
I'm having difficulty in understanding is when I'm creating a new appointment and I select a package how do I save that packages data(array) to the DB so that if I want a collection of appointments I can see what package was assigned to that appointment?
Should I be able to see the relationship from the DB ?
Eloquent provides convenient methods for adding new models to relationships.
you may use the associate method. This method will set the foreign key on the child model:
//...
$appointment = new App\Appointment(['column' => 'value']);
$package = App\Package::find(1);
$appointment->packages()->associate($package);
$appointment->save();
The way you describe it it looks like you have one-to-one relationship between Appointment and Package.
You can attach Package to Appointment using associate method on the relationship.
$appointment = Appointment::find(1);
$package = Package::find(1);
$appointment->package()->associate($package);
Belongs To Relationships
You Can Save Array Data in Relationship
$appointment->package()->createMany($package);

get laravel eloquent model relationships

is there any way to get the defined relationships in eloquent model. I have a situation where I need to get the model relationships so I can update all other eloquent models that relies on a specific id before delete it
There's no unified method to iterate over all registered relationships of a class. You can, however, access all the currently loaded relationships of a model instance (via the ->relations attribute or the getRelations() method), but that's not what you're up to. I'd suggest you take a look at laravel's documentation on inserting and updating relationships. So far that's the best laravel provides out of the box, the rest is developing approaches.
Try this function:
public function getRelations()
You can use
$model->getRelations()
function to get all relations
Also refer below link for details https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Concerns/HasRelationships.html#method_getRelations

Which relation to use in Laravel?

Which relation to use in Laravel to bind two table through third?
When Doctors can be assigned to some Centers. The intermediate table will be as:
doctor_id | center_id
How to create model in Laravel for this case?
You don't need a model for the intermediate table, simply use attach
Example:
$center = Center::create();
$doctor = Doctor::find(1);
$doctor->centers()->attach($doctor->id);
This is a very simple example but should give you the idea, of how to approach it.
All of it of course requires you have set up your Center and Doctor model with the correct many to many relations
Doctor.php model:
public function centers()
{
return $this->belongsToMany(Doctor::class);
}
See the documentation, for more information.
You could obviously create a model called DoctorsCenter and create it manually by doing this, whenever you want to attach a relation.
DoctorsCenter::create(['center_id' => $center->id, 'doctor_id' => $doctor->id]);
I don't see any good reason for doing this, and would not recommend it.
You can use hasMany or belongsTo relationship of Laravel.
See the laravel documentation, for more information

Laravel Eloquent: Access relationship of Original

In Laravel you can use getOriginal() on a model in order to get the original model (before changes since it was queried).
Now I need to access the relationship of that original model... is there a way to do that?
$item = OrderItem::where('id', $id)->with('qualification')->first();
$original_item = $item->getOriginal();
$original_item["qualification"] is not defined. I can access qualification_id though.
getOriginal() method returns array of the model's original attribute values, it is not a model itself, therefore you can not get a relationship.
So you can access the relationship using standard way: $item->qualification, that should not be affected by your changes of the parent model.

Resources