How to relation belongs to in Laravel - laravel

In my project I want show name in category and province table and this table i relation with it in user table.
This is my code.
In controller:
$user=user::with('province','category')->where([['id',$id]])->first();
In model:
//relation with province model (invert relation)
public function province()
{
return $this->belongsTo('App\Model\province');
}
//relation with province model (invert relation)
public function category()
{
return $this->belongsTo('App\Model\category');
}
But in return just id is returned not name and other property.
In output show this:
category_id: 3
province_id: 6

Wrong $user=user::with('province','category')->where([['id',$id]])->first();
//Use
$user=user::with(['province','category'])->where('id', $id)->first();

Put the foreign key and local key to relatioships.
public function province()
{
return $this->belongsTo('App\Model\province','foreign_key','local_key'); // put your FK and LK here
}
public function category()
{
return $this->belongsTo('App\Model\category','foreign_key','local_key'); // put your FK and LK here
}
You can get the result by
$user=user::where('id','=',$id)->first();
if(isset($user))
{
if(isset($user->province))
{
//do whatever you want
}
if(isset($user->category))
{
//do whatever you want
}
}

Related

Laravel get all products from parent category or subcategory using eloquent

I would like to retrieve all products of chosen parent category.Product model have hasmany relation to product_category_mapping table.
If product have subcategory result like,
"MAinCatergory":[
{
id="",
name:"Drinks",
"ChildCategory":[
{
"id":1,
"name":"Juce",
"Products":[{
name:"apple juce",
price:10,
....
}]
}
]
}
]
}
If product under main category only return array like,
"MAinCatergory":[
{
id="",
name:"Drinks",
"Products":[{
name:"apple juce",
price:10,
....
}]
}
}
]
}
category table fields - id,name,parent_id
product table fields - id,name,price,..,
product-category-mapping table fields - id,category_id,product_id
category model
public function children()
{
return $this->hasMany('App\Models\Category', 'parent_id');
}
public function parent()
{
return $this->belongsTo('App\Models\Category', 'parent_id');
}
public function product_category()
{
return $this->hasMany('App\Models\ProductCategoryMapping', 'category_id');
}
product model
public function product_category()
{
return $this->hasMany('App\Models\ProductCategoryMapping','product_id');
}
product-category_mapping
public function product()
{
return $this->belongsTo(Product::class,'product_id','id');
}
public function category()
{
return $this->belongsTo(Category::class,'category_id','id');
}
Something like this might suffice.
App\Models\Category::with('children', 'product_category.product')->get()
Suggestion, try implement pivot many to many relation instead this product_category_mapping, then model relation would change a bit.
For pivot relation, you need to modify the Category model
public function products()
{
return $this->belongsToMany('App\Models\Product', 'product-category-mapping');
}
and in product Model
public function categories()
{
return $this->belongsToMany('App\Models\Category','product-category-mapping');
}
Note:This is not the complete integration, but to give you an idea, for full logic see https://laravel.com/docs/9.x/eloquent-relationships#many-to-many
in your product model add like this:
public function product_categorys(){
return $this->hasMany('App\Models\ProductCategoryMapping','product_id');
}
and in controller you can get inside your function like this Product::with('product_categorys')->get();

nested query with laravel model

I am writing a nested query with Laravel.
Namely First, the Truck information is drawn, then I list the data of the vehicle with "truck_history", there is no problem until here, but I want to show the information of the invoice belonging to the "invoice_id" in truck_history. but I couldn't understand how to query, I want to do it in the model, is this possible? If possible, how will it be done?
"ID" COLUMN IN INVOICE TABLE AND "invoice_id" in "InvoiceDetail" match.
TruckController
public function getTruck($id)
{
$truck = Truck::with(['truckHistory'])->find($id);
return $truck;
}
Truck Model
protected $appends = ['company_name'];
public function companys()
{
return $this->belongsTo(Contact::class, 'company_id', 'id');
}
public function getCompanyNameAttribute()
{
return $this->companys()->first()->name;
}
public function truckHistory(){
return $this->hasMany(InvoiceDetail::class,'plate_no','plate');
}
So you can add another relationship in the InvoiceDetail::class and add in the truck history.
try something like this:
public function truckHistory(){
return $this->hasMany(InvoiceDetail::class,'plate_no','plate')->with('Invoice');
}
Simply add the following relations (if you don't already have them):
Invoice model :
public function truckHistory()
{
return $this->hasOne(InvoiceDetail::class);
}
InvoiceDetail model :
public function invoice()
{
return $this->belongsTo(Invoice::class);
}
And you can get the relation invoice of the relation truckHistory adding a point as separator :
public function getTruck($id)
{
$truck = Truck::with(['truckHistory.invoice'])->find($id);
return $truck;
}

Laravel HasMany relation with parameters

i have a relation between User model and Friend model
User.php
public function friends()
{
return $this->hasMany(Friend::class);
}
the relation actually returns all the records where the foreign key column (user_id) between User and Friend equals the current user's id but i want to return also the records where current user's id is in another column in friends table which's name is friend_id, this is my try
public function friends()
{
return $this->hasMany(Friend::class,'user_id','friend_id');
}
it's actually not returning the correct records
I don't think there is a direct way to that but you could try making 2 relations and merge them into one relation
public function friends() {
return $this->hasMany(Friend::class);
}
public function additionalfriends() {
return $this->hasMany(Friend::class, 'friend_id');
}
public function allfreinds() {
return $this->friends->merge($this->additionalfriends);
}
another solution you might try is
public function friends()
{
return Friend::where(function($query) {
$query->where('user_id',$this->id)
->orWhere('friend_id',$this->id);
});
}

Laravel: Sorting Polymophic Relations

HOW TO
In the Student Controller, how to sort the results by student name?
How to sort the results by student's guardian name?
TABLE STRUCTURE
taxonomies
id
entity_type - It contains the class name of the owning model.
entity_id - It contains the ID value of the student.
students
id
name
guardians
id
student_id
name
CONTROLLER
StudentController.php
public function getStudents()
{
return Taxonomy::with([
'entity',
'entity.guardian'
])
->where('entity_type', 'Student')
->get();
}
MODEL
Taxonomy.php
public function entity()
{
return $this->morphTo();
}
Student.php
public function taxonomies()
{
return $this->morphMany('App\Taxonomy', 'entity');
}
public function guardian()
{
return $this->hasOne('App\Guardian');
}
Guardian.php
public function student()
{
return $this->belongsTo('App\Student');
}
Use sortBy():
$taxonomies = Taxonomy::with('entity.guardian')
->where('entity_type', 'Student')
->get();
// Solution #1: Sort results by student name.
$sortedTaxonomies = $taxonomies->sortBy('entity.name');
return $sortedTaxonomies->values();
// Solution #2: Sort results by student's guardian name.
$sortedTaxonomies = $taxonomies->sortBy('entity.guardian.name');
return $sortedTaxonomies->values();

Laravel BelongsToMany with two pivot table

I have the following table structure:
products
id
product_formats
id
product_id
product_prices
id
product_format_id
market_id
markets
id
A product can have multiple formats, with each having their own price which belongs in a different market. How can I retrieve the list of Markets from the Product model?
I used to have a single pivot table, however now I have two pivot.
class Product extends Model
{
public function markets()
{
return $this->belongsToMany(Market::class);
}
}
Update
To get the result I want, I did the following:
public function markets()
{
return Market::whereIn('id', $this->prices()->distinct()->pluck('market_id')->toArray());
}
However, I'm wondering if there's a way to accomplish this via a relationship.
You need to build relationships in models.
ProductModel:
public function productFormats()
{
return $this->belongTo(ProductFormatsModel::class);
}
ProductFormatsModel:
public function productPrices()
{
return $this->belongTo(ProductPricesModel::class);
}
ProductPricesModel:
public function markets()
{
return $this->hasOne(MarketsModel::class);
}
in Controller:
foreach($product->productFormats as $productFormat)
{
foreach($productFormat->productPrices as $productPrice)
{
var_dump($productPrice->markets);
}
}
For unique markets
in ProductModel:
public function productPrices()
{
return $this->hasManyThrough(
'App\ProductPricesModel',
'App\ProductFormatsModel',
'product_id',
'product_format_id'
'id',
'id'
);
}
in Controller
foreach($product->productPrices as $productPrice)
{
var_dump($productPrice->markets)
}

Resources