How to define multiple belongsTo in laravel - laravel

My table has many foreign key for example prefecture_id, gender_id and status_id.
And I made model for those table.
So I want to define multiple belongsTo method like following for get all data with query builder..
But In fact belongsTo can't use like this.
public function foreign(){
return $this->belongsTo([
'App/Prefecture',
'App/Gender',
'App/Status',
]
}
And if the only way is defining multiple method for belongs to.
How do I get all belongstos data in querybuilder.
Please give me advice.

As far as I am aware, there's not a way to get multiple belongsTo from a single method. What you have to do is make one method for each relationship and when you want to load the relationships you can do the following.
Model
public function prefecture()
{
return $this->belongsTo(\App\Prefecture::class);
}
public function gender()
{
return $this->belongsTo(\App\Gender::class);
}
public function status()
{
return $this->belongsTo(\App\Status::class);
}
Query
// This will get your model with all of the belongs to relationships.
$results = Model::query()->with(['prefecture', 'gender', 'status'])->get();

Related

Laravel BelongsTo relation - where on instance attribute

I have the following model:
class Order extends Model
{
public function user(): BelongsTo
{
return $this->belongsTo(User::class, 'shipping_email_address', 'email_address')
->where('customer_id', $this->customer_id);
}
}
Now when I call Order::with('user')->get(), it doesn't load the users.
I can access the user just fine when using Order::first()->user.
Is it possible to eager load a relationship with a where clause on a model instance attribute (like $this->customer_id)? Or is there another way to make a relationship based on two columns?
You can do this :
Your relation :
public function user()
{
return $this->belongsTo(User::class);
}
Then you can make query like this :
$userId = 5;
$result = Order::whereHas('user',function($q) use ($userId){
return $q->where('id',$userId);
});
Reply to your comment:
Having this relation :
public function user()
{
return $this->belongsTo(User::class);
}
Use this :
Order::with('user')->get()
This will retrieve all orders with its users. If you have some problem on that query then you have a wrong relationship. Make sure you have a foregin key in Orders table, if you dont espcify some foreign key on eloquent relationship, eloquent will understand than foreign key is : user_id, if not, especify putting more arguments to this function :
$this->belongsTo(User::class,...,...);
With function make join according to relationship configuration, just make sure the relation is ok. And all work fine !
If you want to keep your current flow, i would do it like so. Thou the josanangel solution is most optimal.
When getting orders include them using with. All these are now eager loaded.
$orders = Order::with('user');
Now utilize eloquent getters to filter the user by customer_id. This is not done in queries, as that would produce one query per attribute access.
public function getUserByCustomerAttribute() {
if ($this->user->customer_id === $this->customer_id) {
return $this->user;
}
return null;
}
Simply accessing the eloquent getter, would trigger your custom logic and make what you are trying to do possible.
$orders = Order::with('user')->get();
foreach ($orders as $order) {
$order->user_by_customer; // return user if customer id is same
}
Your wrong decleration of the relationship here is what is making this not function correctly.
From the laravel's documentation:
Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with a _ followed by the name of the parent model's primary key column. So, in this example, Eloquent will assume the Post model's foreign key on the comments table is post_id.
in your case the problem is that laravel is searching for the User using user_id column so the correct way to declare the relation is
public function user()
{
return $this->belongsTo(User::class, 'customer_id'); // tell laravel to search the user using this column in the Order's table.
}
Everthing should work as intended after that.
Source: documentation

Eloquent Relationship on the same model

I am using the User model and want to reference other users on a One to Many relationship.
With two models, this would be done by a Many to Many but this attempt at it is obviously wrong:
public function relatedUsers()
{
return $this->belongsToMany(User::class, 'related_user', 'user_id', 'user_id');
}
Is there a better way I can achieve my goal? I don't need an inverse method.
You can use hasMany() or belongsTo() (according to your need) relation for same model relationship
Define hasMany relationship in User model:
public function relatedUsers() {
return $this->hasMany('User','user_id');
}
Example:
Consider you have one User object
$user = User::where('id',$id)->first();
If you want to access related records
$related_users = $user->relatedUsers; // this will return all related users for particular object

How to define Laravel Eloquent relationships via a intermediate table

I have three tables that look like this:
Users
id
name
Things
id
name
ThingsAssigned
id
user_id
thing_id
I want to know how to set up my model relationships and how to write a query where I can pass user_id and get back this structure (will be sent as JSON):
"things": [
{
"name":"thing1"
},
{
"name":"thing2"
}
]
For many to many tables, the naming of the pivot table has to be alphabetical and singular. So the correct name for the table is thing_user. There from it is pretty straight forward.
For your User.php model.
class User {
public function things(): BelongsToMany {
return $this->belongsToMany(Thing::class);
}
}
For the Thing.php model.
class Thing {
public function users(): BelongsToMany {
return $this->belongsToMany(User::class);
}
}
Relations in Laravel is about consistently follow the naming conventions and you have less problems.
To access things, you can do it like so.
$user->things;
To include things with the users you can do.
User::with('things')->get();
After you've set up what has been suggested by #mrhn, you can use it in the following way:
public function randomFunction() {
$user = User::find($user_id);
return $user->things();
}

Getting data from two separate models in laravel

I wanted to get data which is related to an id and I used the find($id) method to get those data, now I wanna get data from two tables which have one to many relationship.
How can I get data which is related to the same id from two table?
I try to this way but it hasn't worked:
public function show($id)
{
$post=Clients::find($id);
return view('pet.shw',['post'=>$post,'pets'=>$post->pets]);
}
Why you dont use with() I have simple solution but maybe not best solution:
Post::with('pets')->where('id',$id)->first();
Maybe below code is work to i dont test it:
Post::with('pets')->find($id);
Of course you should have comments method in your Post Object:
public function pets(){
return $this->hasMany(Pet::class);
}
hope help
You need to first define a relationship between your Client model and Pet model
So, in App\Client, you would have the following relationship:
public function pets()
{
return $this->hasMany(Pet::class);
}
and in App\Pet, you would have the following relationship:
public function client()
{
return $this->belongsTo(Client::class)
}
You should then be able to do this in your Controller:
public function show($id)
{
$post = Client::with('pets')->find($id);
return view('pet.shw')
->withPost($post);
}
and accesses your relationship like this in the pet.shw view:
foreach($post->pets as $pet) {}
For more information read about Eloquent Relationships

I can't make some Eloquent relations to work

Let me first explain the relations of my table, and then I will explain what I cannot do.
So, I have an entity called "Company" it has many "Incomes" which has many "IncomeUnitSale" which has one "IncomeUnitSaleUnitPrice"
Company 1->* Income 1->* IncomeUnitSale 1->1 IncomeUnitSaleUnitPrice
Models:
Company Model
public function Income(){
return $this->hasMany('App\Income');
}
Income Model (table has "company_id")
public function Company(){
return $this->belongsTo('App\Company');
}
public function IncomeUnitSale(){
return $this->hasMany('App\IncomeUnitSale');
}
IncomeUnitSale Model (table has "income_id")
public function Income(){
return $this->belongsTo('App\Income');
}
public function IncomeUnitSaleUnitPrice(){
return $this->hasOne('App\IncomeUnitSaleUnitPrice');
}
IncomeUnitSaleUnitPrice (table has "income_unit_sale_id")
public function IncomeUnitSale(){
return $this->belongsTo('App\IncomeUnitSale');
}
What I am trying to do is the following:
$company = Company::where("id","=",1)->first();
$company->Income->IncomeUnitSale->IncomeUnitSaleUnitPrice
But It says its null, it works till $company->Income->IncomeUnitSale but after that doest't show any relation.
Can somebody please tell me what I am doing wrong?
Thank you!
hasMany relationships will always return an Eloquent Collection object. If there are no related records, it will just be an empty Collection. hasOne and belongsTo relationships will always return either the related Model, or null if there is no related model.
Because some of your relationships are hasMany, you have to iterate the returned Collection to be able to go further. So, instead of $company->Income->IncomeUnitSale->IncomeUnitSaleUnitPrice, you have to:
foreach($company->Income as $income) {
foreach($income->IncomeUnitSale as $sale) {
echo $sale->IncomeUnitSaleUnitPrice->price;
}
}

Resources