remove row from pivot table in laravel - laravel

I have tables (projects, roles, scopes, shifts, users) and a table (project_role_scope_shift_user) as pivot.
I want to delete specific row like:
[project_id = 1 , scope_id = 2 , ... ]
However, detach method doesn't work correctly.
$user->roles()->detach(role) !not working => removes all rows of that role
$user->roles()->detach(role, ['project_id' => $projectId, 'scope_id' => $scopeId, 'shift_id' => $shiftId]); => this does not work too, removes all rows of that role

Try this :
$user->roles()->wherePivot(['project_id' => $projectId, 'scope_id' => $scopeId, 'shift_id' => $shiftId])->detach();

Related

Row inserted but number not

I trying to insert a row in codeigniter and row inserted.
Problem is all row inserted properly but in sql bighint(11) field inserted 0.
I checked properly in array value given.
$data = [
'sku' => $POST['rec1'],
'pruch_price' => $POST['rec2'],
'sell_price' => $POST['rec3']
];
$model->insert ($data);
you should use $_POST[] instead of $POST.
But better yet, don't send $_POST directly to the models, instead use the post request provided by Codeigniter 4.
$data = [
'sku' => $this->request->getPost('rec1'),
'pruch_price' => $this->request->getPost('rec2'),
'sell_price' => $this->request->getPost('rec3')
];
$model->insert($data);

Laravel whereHas not filtering as expected

The 2 models involved are JobRequest and StationJob. Really their relationship is oneToMany. I have a relationship set up for this $jobRequest->stationJobs().
Further to this I need a hasOne relationship latestStation, based on the same model. I need this relationship to filter my collection of JobRequests based on whether the JobRequest has a latestStation equal to a specified station.
I am expecting to get an empty list of JobRequests because I know the latestStation is equal to id 3 and I am filtering for id 2. Instead I get the jobRequest, with latestStation id 3 even though I am filtering for 2.
Relationship
public function latestStationTest()
{
return $this->hasOne(StationJob::class)->whereNotNull('finished')->latest();
}
Controller
$stationId = $request->station_id;
$jobRequests = JobRequest::with(['latestStationTest'])->whereHas('latestStationTest', function($query) use ($stationId) {
$query->where('station_id', $stationId);
})->get();
Query Result
[2020-10-17 07:39:07] local.INFO: array (
0 =>
array (
'query' => 'select * from `job_requests` where exists (select * from `station_jobs` where `job_requests`.`id` = `station_jobs`.`job_request_id` and `station_id` = ? and `finished` is not null)',
'bindings' =>
array (
0 => 2,
),
'time' => 1.0,
),
1 =>
array (
'query' => 'select * from `station_jobs` where `finished` is not null and `station_jobs`.`job_request_id` in (1) order by `created_at` desc',
'bindings' =>
array (
),
'time' => 0.5,
),
)
I've tried...
Switching with() before or after whereHas makes no difference.
adding ->where() to with() selects the StationJob with the specified id, instead of checking if the latestStation id is equal to the specified id.

how select between tow number 1 and 3 in faker laravel?

I do not need 2 .I want just 1 or 3 in user_id because it is foreign key and have just 1 and 3 number
'user_id' => rand(1,3)->not(2),
'resnumber' => rand(1000000,5000000),
'price' => rand(500000,1000000),
'payment' => rand(0,1),
'created_at' =>$faker->dateTimeBetween('-7 months','now')
You could use randomElement()
'user_id' => $faker->randomElement([1, 3]),
https://github.com/fzaninotto/Faker#fakerproviderbase

Select two lists as one list in ASP.NET Core linq

I am trying to create a query with ASP.NET Core EF Core and Linq that would give me a List of users based on two different lists, something like this:
return await _context.Users
.Include(u => u.PropertyOwners)
.ThenInclude(po => po.Property)
.ThenInclude(p => p.PropertyTenantLeases)
.Include(u => u.PropertyOwners)
.ThenInclude(po => po.Owner)
.Where(u => u.Id == userID)
.Select(u => new List<User>()
{
u.PropertyTenantLeases.Select(ptl => ptl.Tenant).ToList()
u.PropertyOwners.Select(po => po.Owner).ToList()
}).FirstOrDefaultAsync();
The tables that are used in this query are connected in the following way:
Everything is fine with this query except for the Select, with the Select I am trying to achieve that it returns a list of all the tenants in the PropertyTenantLeases table which is a junction table togheter with all the Owners form the PropertyOwners junction table (both Tenant and Owner are IdentityUser classes. When I right this query like this I get the following error:
The best overloeaded Add method 'List<User>.Add(User)' for the collection initializer has some invalid arguments
and also
Argument 1: cannot convert from 'System.Collections.Generic.List<RosyMasterDBManagement.Models.User>' to 'RosyMasterDBManagement.Models.User'
Joining two list is called a union in Linq -- I believe that is what you want:
note: I still can't test this since you gave a picture of the data model instead of the code that would allow me to be certain of how to implement. expect the fields to be named incorrectly etc.
var ownerlist = _context.Users
.Include(u => u.PropertyOwners)
.ThenInclude(po => po.Owner)
.ToList();
var tenantlist = _context.Users
.Include(u => u.PropertyOwners)
.ThenInclude(po => po.Property)
.ThenInclude(p => p.PropertyTenantLeases)
.ThenInclude(po => po.Tenant)
.ToList();
return ownerlist.Union(tenantlist);
I don't believe you need await() since ToList() forces it to not be lazy. But I could be wrong about that.

Laravel eager loading returns all results when querying realtionship

I want to get products with a seri name contains a certain word. However it returns all products. Matching serie name condition appears to be array under each related product; for the rest of products it is just a blank "serie" key.
$products=Product::with(array(
'serie'=>function($query)
{
$query->where('name','like','%unky%');
}))
->get()->toArray();
and array returned is like
[0] => Array
(
[id] => 1
[updated_at] => 2014-02-14 22:26:04
[created_at] => 0000-00-00 00:00:00
[brand_id] => 1
[cat_id] => 1
[serie_id] => 1
[devices_ids] => 1
[color_code] => #BEB991
[barcode] => 8699131462430
[title] => Funky Charlie iPhone 5/5S Kılıfı
[desc] => Sert 6 gr
[price] => 29.90
[serie] => Array
(
[id] => 1
[updated_at] => 2014-02-14 22:18:31
[created_at] => 0000-00-00 00:00:00
[name] => Funky
)
)
[1] => Array
(........
[5] => Array
(
[id] => 6
[updated_at] => 2014-02-14 22:46:10
[created_at] => 0000-00-00 00:00:00
[brand_id] => 1
[cat_id] => 1
[serie_id] => 2
[devices_ids] => 1
[color_code] => red
[barcode] => 8699131462546
[title] => Bonjour Kırmızı iPhone 5/5S Kılıfı
[desc] => Sert 6 gr
[price] => 24.90
[serie] =>
As you can see serie key is empty.
What i want is only to bring products with matching serie name and does not bring products like with id"5".
What i am doing wrong?
Thanks
I think that instead of using Model::with(), you want to instead filter the Model, based on the related model, so you should use Model::whereHas()
$products = Product::whereHas('serie', function($query)
{
$query->where('name','like','%unky%');
})->get()->toArray();
Eager loading constraints do not put a constraint on the results of the model - it constraints the related model. In your case, you get all Products. But if you try to access the Series of a Product, you will only get those Series that are true to your condition.
If you need to access the Series too and do not only need the Products, I would make the query like this:
$products=Product::with(array(
'serie'=>function($query)
{
$query->where('name','like','%unky%');
}))
->whereHas('serie', function($query) {
$query->where('name','like','%unky%');
})
->get()->toArray();
In this case, you get only the Products that are linked to a Serie whose name is like %unky% and you get only the related Series that hold to the same condition.
To sum this up: whereHas restricts the list of Products based on the condition, whereas the Eager Loading constraint restricts only the list of Series for each Product.

Resources