Query Laravel Eloquent many to many where all id's are equal - php

I making a project based on Laravel and have the tables: companies, attributes, and attribute_company related as Many To Many relation when attribute_company use as a pivot table to connect companies and attributes tables.
I get an array of attribute_id's from the client and I need to get results of the companies that has the whole attributes exactly.
The only solution I found is to query whereHas combined with whereIn inside like this:
Company::whereHas('attributes', function (Builder $query) use ($atts_ids) {
$query->whereIn('attribute_id', $atts_ids);
})->get();
This query will return companies if at least one attribute_id found (which is not what I am looking for).
It would be great if anybody can make it clearer for me.
Thank you all in advance :)

One possible solution:
$company = new Company();
$company = $company->newQuery();
foreach($atts_ids as $att_id)
{
$company = $company->whereHas('attributes', function (Builder $query) use ($att_id) {
$query->where('attribute_id', $att_id);
});
}
$company = $company->get();

Related

Laravel, search exact same substring in eloquent query

I have a table like this
Teacher Table
What I am trying to do is to get the row which contains the subjects 1(or any other number like 7,8 etc.)
This is what I have tried in my controller.
public function allTeachers($sub_id) //receiving $sub_id(to be searched)
{
$teachers_all=Teacher::where('subjects','like','%'.','.$sub_id.'%')->latest()->paginate(50);
dd($teachers_all);
}
The problem here is that, I am getting all the rows which contains subjects as '1',e.g. if it is '3,11,22' or '41,5' it gets selected.
But what I am trying to achieve is it should only return where subjects string contains '1' followed by any other number after ',' or '1,2,44,31,23' etc.
I am using laravel, I hope I made the question clear.
The solution to your question would be either to use find_in_set or concat to fill some missing commas and then search for the value:
Teacher::whereRaw('find_in_set("' . $sub_id . '", subjects) <> 0')
->latest()
->paginate(50);
or
Teacher::whereRaw('concat(",", colors, ",") like "%,' . $sub_id . ',%"')
->latest()
->paginate(50);
That being said, #bromeer's comments hold true in any case. MySQL isn't around comma-separated values in fields. Both examples shown above aren't an ideal solution. You should look into relationships a bit more.
I suggest using a many-to-many relationship in your case. For that, create a pivot table called teacher_subject and add the relation to your Teacher model:
public function subjects()
{
return $this->belongsToMany(Subject::class);
}
To find any teachers teaching a specific subject, use whereHas like this:
Teacher::whereHas('subjects', function (Builder $query) use ($sub_id) {
$query->where('id', $sub_id);
})->latest()->paginate(50);

How to detach on many element with Laravel Eloquant

I have a relationship many to many with the table Screen and Media with a pivot table Media_Screen.
I want to remove the data with the screens' id in $id_screens from the pivot table.
I did like this :
$id_screens = [4,5];
$screens = App\Screen::whereIn('id', $id_screens)->get();
foreach($screens as $screen)
{
$screen->medias()->detach();
}
It works but I'm wondering if there is not a better way to do? I tried something like this but it didn't work :
$id_screens = [4,5];
$screens = App\Screen::whereIn('id', $id_screens)->get();
$screens->medias()->detach();
You can mass detach the relationship by querying on pivot table. It'll reduces number of queries you do in the loop. In your case, you can use below code for example.
$screens_id = App\Screen::whereIn('id', $id_screens)
->select('id')
->get()
->pluck('id');
\DB::table('Media_Screen')->whereIn('id_screen', $screens_id)->delete();
You may try "high order messages" as documented here:
$id_screens = [4,5];
$screens = App\Screen::find($id_screens);
$screens->each->medias()->detach();

Match array of ids from pivot table

Scenario
I have 3 main tables Employees,Jobs,Skills. Employees and Jobs has many-to-many relationship with Skills table.
So, an employee can have skills 1,2,3,5. A job may requires skills 1,3,5.
Now my question is how can I match the id's in an eloquent query. Like, if I want to search all the employees for a job requiring skills 1,3,5, it should search all the employees having all those skills(1,3,5)
You said you have an array of IDs, so use multiple whereHas():
$employees = Employee::JobLocations($jobZipId);
foreach ($skillIds as $id) {
$skilledEmployees = $emloyees->whereHas('skills', function ($q) use ($id) {
$q->where('id', $id);
});
}
$skilledEmployees = $skilledEmployees->get();
You can do it like, I am taking $job as already a defined object.
Employee::whereHas('skills', function($q) use($job) {
$q->whereIn('id', $job->skills->lists('id')->toArray());
})->get();
Update
In case of Laravel 5.3 and up, the method lists won't work (as its is removed) so you can also use pluck method instead of lists.
Hope this helps you to solve your problem.

laravel 5.2 eloquent order by on relationship result count

I have two tables website_link and website_links_type. website_link is related website_links_type with hasmany relationship.
$this->website_links->where('id',1)->Paginate(10);
and relationship
public function broken()
{
return $this->hasMany('App\Website_links_type')->where('status_code','!=',"200");
}
Now I want to get result from website_link table but Orderby that result on count of broken relationship result.
There are many ways to solve this problem. In my answer I'll use two I know.
You can eagerload your relationship and use the function sortBy(). However I don't think you can use the paginate() functionality with this solution.
Example:
$results = Website_link::with('website_links_type')->get()->sortBy(function ($website_link) {
return $website_link->website_links_type->count();
});
See this answer
You can also use raw queries to solve this problem. With this solution you can still use the pagination functionality (I think).
Example:
$results = Website_link
::select([
'*',
'(
SELECT COUNT(*)
FROM website_links_type
WHERE
website_links_type.website_link_id = website_link.id
AND
status_code <> 200
) as broken_count'
])
->orderBy('broken_count')
->paginate(10);
You may have to change the column names to match your database.
You can not put WHERE condition in model file.
You just give relationship hasMany in model file.
And use where condition in controller side.
Refer this document.
Try this
Model file:
public function broken()
{
return $this->hasMany('App\Website_links_type');
}
Controller file:
$model_name->website_links->where('id',1)
->where('status_code','!=',"200")
->orderBy('name', 'desc')
->Paginate(10);

Laravel 4.1 WhereIn w/ Many to Many Relation and Conditionals?

I am working on an application where part of it needs to search through a number of different fields on the same model with AND - AKA find age whereBetween $from and $to AND where gender is $gender. Where I am getting lost is this model has a many to many relationship with Category and I need to filter by category in the same query. I am trying to do this in one query because it needs to be pretty fast.
Here is what I have so far:
$categories = Input::get('categories');
$query = Program::with('categories')->whereIn('category', $categories)->query();
if ($ages = Input::get('ages')) {
$query->whereBetween('age',array($from,$to));
}
if ($gender = Input::get('gender')) {
$query->where('gender','like', $gender);
}
// Executes the query and fetches it's results
$programs = $query->get();
I have put this together from so many different sources that I would like to know if this even works, or if it is the most efficient method possible. There is of course a table programs, a table categories, and a table program_category with columns id, program_id, and category_id.
Thanks in advance for your help!
So, in the end figured it out:
$query = Program::whereHas('categories', function($q) use ($categories)
{
$q->whereIn('categories.id', $categories);
});
'categories' is the name of the relationship function on my Program model. $categories is my array of category ids. Thanks again for your help.
This will work if fields are available in the right table as you queried for and you may write it like this:
$categories = Input::get('categories');
$query = Program::with('categories')->whereIn('category', $categories);
// declare $from and $to if not available in the current scope
if ($ages = Input::get('ages')) $query->whereBetween('age', array($from,$to));
if ($gender = Input::get('gender')) $query->where('gender', $gender);
// Executes the query and fetches it's results
$programs = $query->get();

Categories