How to access multiple model data from an eloquent call - laravel

I currently have a product table with the following columns:
id, product_name, product_type, description
I also have three more tables:
medias, attributes, coatings
each of those tables has an id, name, description, img
Each product created din the product table will have multiple, medias, attributes and coatings. To address this I created a table product_relations which contains the columns:
id, product_id, media_id, attribute_id, coating_id
From here I thought I would make a call to product_relations with the product_id and then pull each record so I can access the data. However I'm stuck on how I would do this as an eloquent relationship. Would I do separate has many's in my Product_Relation model like so:
public function media()
{
return $this->hasMany('App\Media');
}
public function attributes()
{
return $this->hasMany('App\Attributes');
}
etc? Or is there a simpler way to build this to access all that at once?

Related

One To Many with pivot not possible. How to redesign relationships?

I would like to do the following:
Product can have one Supplier. The Supplier contains some data like a name. Additionally there is a pivot-value that should be stored for Supplier that is assigned to Product (e.g. a delivery_service-string).
Example:
Product: A yummy Banana
Supplier: Banana Inc
-> If the Product "A yummy Banana" is supplied by Supplier it should be delivered by DHL. The important thing: You can not add DHL as a field to Supplier, as each Product to Supplier-relation should have it's own delivery-service-field.
As there can be many Products but each Product can only have one Supplier I thought about something like this:
Product
Schema:
- id
- supplier_id
Relation
public function supplier()
{
return $this->belongsTo(Supplier::class);
}
Supplier
Schema:
- id
- name
Relation
public function products()
{
return $this->hasMany(Product::class);
}
This works, but unfortunately I can not store pivot data in the supplier() relation.
At the moment I could imagine to store the value not in a pivot table but in a new row in the Product's schema. But I don't think this is the best way.
Any suggestions? :-)
One item have many childs
This is one-to-many
You need to store item_id in your child table
Item Table
id, name
Child Table
id, item_id, type
If you have a case EG
Each child can have a favorite item then you will have to create a many-to-many relation between them. (Which will be a separate relation)
Create a table "child_item" (pivot)
Child Item Table
child_id, item_id
then create a relation in your laravel
class User extends Model{
...
public function favorites(){
return $this->belongsToMany(Items::class); // Include the path using "use" on top
}
}
So now you get your 2 relations between child and item
One item can have many children
Many children can mark items as favorites

How do you combine the following three tables with eloquent in laravel?

How to combine 3 Many to Many tables with eloquent in the laravel
Hi Friends, please help me,
How do you combine the following three tables with eloquent in laravel?
The following table structure and figures:
(https://i.stack.imgur.com/BfISA.jpg)
Member table structure
{member_id: primary key, name, created_at, updated_at}
List table structure
{list_id: primary key, member_id: foregn key, price_id: foreign key, created_at, updated_at}
Price table structure
{price_id: primary key, name_price, created_at, updated_at}
Can you give me sample source code for view.blade, controller and model.
Thank you, your answer is very meaningful
in your member model add relationship function list(). Then in your list model add relationship function price then use below code
app\Member.php
public function list(){
return $this->hasMany('App\List', 'member_id');
}
app\List.php
public function price(){
return $this->hasMany('App\Price', 'price_id');
}
in your controller
$result = Member::with(['list.price'])->get();
it will give you a member list with list and price table data.

Laravel whereHas ManyToMany relation but then order by a value in the third table

I have 3 tables
entry (
id,
title,
other_stuff)
entry_award (
id,
award_id,
entry_id)
award (
id,
name,
type)
I am trying to create a laravel query which lets me get all the entries that have awards, and order them by award.type ASC
$Entries = Entry::with('award')
->whereHas('award', function ($query) {
$query->orderBy('award.award_id','ASC');
})->paginate(20);
But this doesn't work.
This is the sql version of it
SELECT DISTINCT entry.*
FROM entry, award, entry_award
WHERE entry.id = entry_award.entry_id
AND award.id = entry_award.award_id
ORDER BY award.type ASC;
Now I tried to just use the raw sql for it, but the problem seems to be that laravel does not then recognize the result as Entry models/objects. And i need to get other Entry relations later on in the html via blade.
So how can I either make a query-builder query that gets me all entries that have awards and orders them by award.type value
or use the raw sql but have Laravel see it as an array of Entry
objects instead of just an array of JSON values.
class Entry extends Model {
public function entry_award(){
return $this->belongsToMany('App\Award', 'entry_award');
}
}
class Award extends Model {
public function entries() {
return $this->belongsToMany('App\Entry', 'entry_award');
}
}

Laravel sort by pivot table column

I am trying to sort an eloquent query in laravel by a column from the pivot table.
Basically as long as the product is favorited by the user, it is added to the pivot table, and it should first show the favorited ones, and then the remaining ones. Since I will be using foreach in the blade.
products table contains these columns:
id, category, product_name, priority, status, created_at, updated_at
users table contains these columns:
id, name, email, created_at, updated_at
with the following in the users model:
public function favorites()
{
return $this->belongsToMany(Products::class, 'favorites', 'user_id', 'product_id')
->withTimeStamps();
}
favorites table contains these columns:
id, user_id, product_id, created_at, updated_at
In the controller, the eloquent query is currently:
$productinprogress = Products::all()
->sortByDesc("priority")
->where('status', 'inprogress');
I am just confused as to how to tackle this.
Your help is appreciated. Thank you so much.
I think you should make two queries to avoid loading duplicate products, first one for favorite products, second one should be some thing like this:
Products::all()->sortByDesc("priority")->where('status', 'inprogress')->whereNotIn('id', $favorite_products);
and then in the blade file, you make two foreach, first one for favorites, and 2end for others.
you can use something like bellow:
$productinprogress = Products::all()
->where('status', 'inprogress')
->sortByDesc("priority");
and if you want an efficient solution using eager loading and loading favorites too, use following code
$productinprogress = Products::all()
->with('favorites')
->where('status', 'inprogress')
->sortByDesc("priority");

A BaseClass extends from Eloquent to handle complicated search condition in laravel

Previous description of my problem is wrong. So I delete it and write a new one.
There are several tables, following are their structures
Table1: id, name
Table2: id, name, date1, date2
Table3: id, name, desc
maybe more tables...
And some html pages, each one references to a table. Every page has one or more search box to search data in related table. I use Ajax to handle the search work. I take some examples as below
Page related table search columns http params
Page1: Table1 id, name q={"id": 1, "name":"bill"}
Page2: Table2 id, date1, date2 q={"id": 1, "date1":"2014-7-19", "date2":"2014-7-20"}
Page3: Table3 id, name q={"id": 1, "name":"bill", "desc":"boss"}
Then I want to create a BaseModel extends from Eloquent, then all other specific Models extends from BaseModel.
I hope there will be a "search" method it can handle all of complicated search actions in BaseModel.
It's hard to suggest a good solution since you don't really tell us, what needs to be done.
This is the most straightforward solution for you, using query scopes:
// BaseModel extending Eloquent Model
public function scopeSearch($query, $jsonSearch)
{
$wheres = $this->parseSearch($jsonSearch);
$query->where($wheres); // WHERE X = Y AND Z = A ...
}
protected function parseSearch($jsonSearch)
{
// validate your input here, make sure it's correct according to your needs
}
Then:
// single result
AnyModel::search($yourJson)->first();
// collection
AnyModel::search($yourJson)->get();
// you can chain more methods if you like
AnyModel::search($yourJson)->where('x', 'y')->orderBy('x')->get();

Resources