Delete/detach first pivot table records - php

Case
Laravel 5.3
Having a pivot table between Cart & Product with an additional column:
id - cart_id - product_id - item_id (additional column)
1 - 1 - 1 - 5
2 - 1 - 1 - 6
3 - 1 - 1 - 7
4 - 2 - 1 - 8
Normally you detach a pivot table record using:
$product->carts()->detach($cartId);
But in this case, there are several pivot table records with the same cart & product id
Problem
Lets say I want delete to row 1.
What I hoped to work was either one of these:
$product->carts()->detach($itemId);
or
$product->carts()->detach($cartId)->first();
If I query the pivot table based on cart_id & product_id, call the first & run delete() on that query result a Call to undefined method stdClass::delete() will be returned
$firstItem = DB::table('cart_product')
->where('cart_id', $cart_id)
->where('product_id', $product->id)
->first();
$firstItem->delete();
Although when I dd() $firstItem after querying the data, it will return a (correct) object
{#238 ▼
+"id": 1
+"cart_id": 1
+"product_id": 1
+"item_id": 5
}

You can't use detach() if you want to delete just one row in this table.
If you want to delete just first item, just use this:
DB::table('cart_product')
->where('cart_id', $cart_id)
->where('product_id', $product->id)
->take(1)
->delete();
Or from your code:
$id = DB::table('cart_product')
->where('cart_id', $cart_id)
->where('product_id', $product->id)
->first()->id;
DB::table('cart_product')
->where('id', $id)
->delete();

Related

Laravel wherenotexists returning null

I have the following piece of code
$not_paid = Tenant::where('property_id', $property_id)
->whereNotExists(function ($query) use ($property_id) {
$query->select('user_id')
->from('rent_paids');
})
->get();
which is supposed to get all the tenants in a certain property, look them up in the rent_paids table and return the users who are not in the rent_paids table, as follows:
tenants table
Id
user_id
property_id
1
1
1
2
2
1
3
3
1
rent_paids
Id
user_id
property_id
amount_paid
1
1
1
3000
I want to be able to return the users in the tenants table and not in the rent_paids table. In this case, users 2 and 3. But the above code returns an empty array.
You're missing the where clause to tie it back to the original table.
$not_paid = Tenant::where('property_id', $property_id)
->whereNotExists(function ($query) use ($property_id) {
$query->select('user_id')
->from('rent_paids')
->whereColumn('tenants.user_id', '=', 'rent_paids.user_id');
})
->get();

How to grab only latest update record from data table in Laravel 5.6?

I have following table name as projects like this structure,
id name adtype created_at updated_at
1 gobba 1 2018-02-25 2018-02-25
2 manna 0 2018-04-25 2018-04-25
3 alaya 1 2017-12-28 2017-12-28
I need grab only one result witch related to latest updated record and adtype == 1, I code following controller, for this,
public function showad()
{
$projects = Vehicle::with('uploads')
->where('adtype','=',1)
->latest('updated_at');
return view('vehicles.slider')->withProjects($projects);
but this working but not filtering latest updated records. how can correct this?
Try using ORDER BY and LIMIT:
$projects = Vehicle::with('uploads')
->where('adtype', '=', 1)
->orderBy('updated_at', 'desc')
->take(1)
->get();
This should correspond to the following raw MySQL query:
SELECT *
FROM uploads
WHERE adtype = 1
ORDER BY updated_at DESC
LIMIT 1;

How to get data from another table using ID from another table

I would like to get a data from a table to another table using it's primary key.
products_table:
id name type_id date_added
1 item1 2 1234
2 item2 2 5678
3 item3 1 0000
product_type_table:
id type_name
1 type1
2 type2
3 type3
I am querying the first table using this code:
Products::select('name','type_id')->where('id',$id)->get()
Now, how do I automatically get the type_name from the product_type_table using the type_id from the products_table?
As Jack Skeletron pointed out, the Laravel documentation has examples for joining 2 or multiple tables.
In your case
$products = DB::table('products_table')
->join('product_type_table', 'products_table.type_id', '=', 'product_type_table.type_id')
->select('products_table.name, products_table.type_id')
->where('id', $id)
->get();
you can use left join.
DB::table('product_type_table')
->leftJoin('products_table', 'product_type_table.id', '=', 'products_table.type_id ')->where('product_type_table.id',$id)
->get();
In Product Model add Below code for joining 2 tables:
use App\Models\ProductType;
public function type()
{
return $this->belongsTo(ProductType::class);
}
and change the line:
Products::select('name','type_id')->where('id',$id)->get()
to
Products::select('name','type_id')->with(['type' => function($q){
return $q->select('type_name');
}])->where('id',$id)->get()
Hope this works for you.

Multiple leftJoins using Laravel's Query Builder producing incorrect counts

I am using Laravel 5.4's Query Builder to perform a series of leftJoins on three tables. Here are my tables:
items
id type title visibility status created_at
-- ---- ----- ---------- ------ ----------
1 1 This is a Title 1 1 2017-06-20 06:39:20
2 1 Here's Another Item 1 1 2017-06-24 18:12:13
3 1 A Third Item 1 1 2017-06-26 10:10:34
count_loves
id items_id user_id
-- ------- -------
1 1 2
2 1 57
3 1 18
count_downloads
id items_id user_id
-- ------- -------
1 1 879
2 1 323
And here is the code I am running in Laravel:
$items_output = DB::table('items')
->leftJoin('count_loves', 'items.id', '=', 'count_loves.items_id')
->leftJoin('count_downloads', 'items.id', '=', 'count_downloads.items_id')
->where('items.visibility', '=', '1')
->where('items.status', '=', '1')
->orderBy('items.created_at', 'desc')
->select('items.*', DB::raw('count(count_loves.id) as loveCount'), DB::raw('count(count_downloads.id) as downloadCount'))
->groupBy('items.id')
->get();
When I return the results for this query, I am getting the following counts:
count_loves: 6
count_downloads: 6
As you can see, the actual count values should be:
count_loves: 3
count_downloads: 2
If I add another entry to the count_loves table, as an example, the totals move to 8. If I add another entry to the count_downloads table after that, the totals jump to 12. So, the two counts are multiplying together.
If I die and dump the query, here's what I get:
"query" => "select 'items'.*, count(count_loves.id) as loveCount,
count(count_downloads.id) as downloadCount from 'items' left join
'count_loves' on 'items'.'id' = 'count_loves'.'items_id' left join
'count_downloads' on 'items'.'id' = 'count_downloads'.'items_id'
where 'items'.'visibility' = ? and 'items'.'status' = ? group by
'items'.'id' order by 'items'.'created_at' desc"
How do I perform multiple leftJoins using Query Builder and count on several tables to return the proper sums?
NOTE:
This is intended as a HELP answer not the total absolute answer but I could not write the code in a comment. I am not asking for votes (for those who just can't wait to downvote me). I have created your tables and tried a UNION query on raw sql. I got correct results. I dont have laravel installed, but maybe you could try a UNION query in Laravel.
https://laravel.com/docs/5.4/queries#unions
select count(count_downloads.user_id)
from count_downloads
join items
on items.id = count_downloads.items_id
UNION
select count(count_loves.user_id)
from count_loves
join items
on items.id = count_loves.items_id

Laravel 5 - constraining by parent relations

Say I have a reservations table
id - restaurant_table_id - guest_id
1 - 3 - 5
2 - 4 - 7
And then an orders table
id - reservation_id - item_id
1 - 1 - 2
2 - 2 - 4
How can I pull orders that belong to a restaurant table?
I have tried:
$orders = ReservationOrders::with(['reservation' => function ($query) use ($restaurant_table_id) {
$query->where('restaurant_table_id', $restaurant_table_id);
}])
->get();
But the results included orders for all restaurant tables.
You can filter on relation's attributes using Eloquent's whereHas() method - you can get more information here: http://laravel.com/docs/5.1/eloquent-relationships
In your case sth like the code below should help:
$orders = ReservationOrders::with('reservation')->whereHas('reservation', function($query) use($restaurant_table_id) {
$query->where('restaurant_table_id', $restaurant_table_id);
})->get();

Categories