Laravel Where Condition on Grand Parent Eloquent Relation - laravel

I have 4 tables:
Account (id, name)
Type (id, account_id, name)
Category (id, type_id, name)
Money (id, category_id, date, amount)
And I defined the relations at model
But my problem is how to get money data with account id 2?
Account::find(2)-> type()-> category()->money
Is not working

Assuming you created your relationships, you can do it this way:
$account = Account::with('type.category.money')->find(2);
and to display money you can now use:
echo $account->type->category->money->amount;
In above echo I of course assume for each record you have data in all those tables. If not, you'll need to add extra checking to make sure you don't display property for null

You can also go about this from the other direction if you only need the final result of 'money' and have the inverse relationships setup on the models.
$money = Money::whereHas('category.type.account', function ($q) use ($id) {
$q->where('id', $id);
})->get();
// get() or first() depending whether these relationships return many
Laravel Docs - Eloquent Relationships - Querying Relationships - Querying Relationship Existence

Related

Laravel Lumen eloquent left join returns joined table data rather than primary able data

I have two tables company and courses table
The table has the following fields
companies table
id, full_name, email, deleted_at
and courses table
courses table
id, company_id, course_name,deleted_at
Now i would like to retrieve all courses which company is not deleted. So in my controller i have added
public function index(Request $request){
$query = Courses::query();
$query = $query->leftJoin('companies','companies.id','=','courses.company_id');
$query->whereNull('companies.deleted_at');
if($request->get('filter_name')){
$query = $query->where('courses.name', 'like', '%' . $request->get('filter_name') . '%');
}
return response()->json($query->paginate($request->get("perPage")));
}
When i run the above it returns companies data rather than courses. Where am i going wrong or what am i missing out?
If you have use eager loading in both of your model, you can use this kind of approach.
$all_course = Courses::with(['company', function($query) {
return $query->whereNotNull('deleted_at');
}])->get();
As you can see, I query in the Courses model to return all the courses but I added some filter in the company relationship. where in I used whereNotNull to get only the company that's not deleted.

laravel eloquent with pivot and another table

I have 4 table categories, initiatives, a pivot table for the "Many To Many" relationship category_initiative and initiativegroup table related with initiatives table with initiatives.initiativesgroup_id with one to many relation.
With pure sql I retrive the information I need with:
SELECT categories.id, categories.description, initiatives.id, initiatives.description, initiativegroups.group
FROM categories
LEFT JOIN category_initiative ON categories.id = category_initiative.category_id
LEFT JOIN initiatives ON category_initiative.initiative_id = initiatives.id
LEFT JOIN initiativegroups ON initiatives.initiativegroup_id = initiativegroups.id
WHERE categories.id = '40'
How can I use eloquent model to achieve same results?
Since you have such a specific query touching multiple tables, one possibility is to use query builder. That would preserve the precision of the query, retrieving only the data you specifically need. That would look something like this:
$categories = DB::table('categories')
->select([
'categories.id',
'categories.description',
'initiatives.id',
'initiatives.description',
'initiativegroups.group',
])
->leftJoin('category_initiative', 'categories.id', '=', 'category_initiative.category_id')
->leftJoin('initiatives', 'category_initiative.initiative_id', '=', 'initiatives.id')
->leftJoin('initiativegroups', 'initiatives.initiativegroup_id', '=', 'initiativegroups.id')
->where('categories.id', '=', 40)
->get();
In your models define the relationships:
Category.php model
public function initiatives()
{
return $this->belongsToMany('App\Initiative');
}
Initiative.php model (If has many categories change to belongs to many)
public function category()
{
return $this->belongsTo('App\Category');
}
Then maybe change your initiativegroup -> groups table, and then create a pivot table called group_initiative. Create model for group. Group.php and define the relationship:
public function initiatives()
{
return $this->belongsToMany('App\Initiative');
}
Then you can also add the following relationship definition to the Initiative.php model
public function group()
{
return $this->belongsTo('App\Group');
}
That should get you started.
for the record..
with my original relationship, but changing table name as alex suggest, in my controller:
$inits = Category::with('initiative.group')->find($id_cat);
simple and clean

OneToMany + ManyToMany

I have 3 main tables (sellers, stores, products), and there is another table for relation between stores and products (store_product)
A seller has many stores (One to Many relationship)
A store has many products, but any of those products can be assigned to multiple stores, maybe in another seller's stores (Many To Many relationship)
Now, I have a confusion, I want to get all products for a specific seller.
If you defined the reserve of the relationships, you can do:
// your seller's id
$seller_id = 1;
// get your products
$products = Product::whereHas('stores.seller', function ($query) use ($seller_id) {
$query->where('id', $seller_id);
})->get();
Update
To get the count of products under every seller, you could use the withCount() method, just like this:
$sellers = Seller::withCount(['stores' => function ($query){
$query->withCount('products');
})->get();
which will place a {relation}_count column inside the stores relationship of your resulting models. In this case, products_count:
foreach ($sellers as $seller) {
echo $seller->stores->first()->products_count;
}
What you need is the builder function whereHas('relation', $callback). With it your query is very straight forward:
$products = Product::query()
->whereHas('stores.seller', function ($query) use ($sellerId) {
$query->where('sellers.id', $sellerId);
})
->get();
Apparently using sellers.id (where sellers is the table name) is important because you most likely have a column called id on all three tables. If you omit the table name, the query will fail.

Laravel 4/5, order by a foreign column

In Laravel 4/5 how can order a table results based in a field that are connected to this table by a relationship?
My case:
I have the users that only store the e-mail and password fields. But I have an another table called details that store the name, birthday, etc...
How can I get the users table results ordering by the details.name?
P.S.: Since users is a central table that have many others relations and have many items, I can't just make a inverse search like Details::...
I would recommend using join. (Models should be named in the singular form; User; Detail)
$users = User::join('details', 'users.id', '=', 'details.user_id') //'details' and 'users' is the table name; not the model name
->orderBy('details.name', 'asc')
->get();
If you use this query many times, you could save it in a scope in the Model.
class User extends \Eloquent {
public function scopeUserDetails($query) {
return $query->join('details', 'users.id', '=', 'details.user_id')
}
}
Then call the query from your controller.
$users = User::userDetails()->orderBy('details.name', 'asc')->get();

Update many records in a laravel relationship

I have 4 tables that I'm trying to work with in Laravel and I can't figure out how to use eloquent to execute a particular query. I want to update all orders that belong to a user (through product_id) and that have null payout_id.
This raw sql statement works but I'm not sure how to use eloquent for this..perhaps sync?
UPDATE order_items i JOIN products p on (i.product_id = p.id) SET i.payout_id = null where p.user_id = 3
User Model
Product Model
FK: user_id
Order Model
FK: product_id
FK: payout_id
Payout Model
I would really appreciate any help!
First define a function orders in User Model
public function orders()
{
return $this->hasManyThrough('Orders', 'Product','user_id','product_id');
}
User::where('id','=',$userid)->with(array('orders'=>function($query){
$query->where('payout_id','=',0)->update(array('payout_id'=>$updatevalue));
}))->first();
You need to create a model for your tables i and p, see http://laravel.com/docs/eloquent for full information on model creation.
In the model for i you would then create a relationship to p:
public function p()
{
return $this->('p','id','product_id');
}
You can then run your query as follows:
$results = i::with('p')
->where('user_id', '=', 3)
->update(array('payout_id' => null));

Resources