Laravel, search exact same substring in eloquent query - php

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);

Related

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

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();

Laravel 5.4 where clauses if $request->jobTitle !null?

I built small search form helps me search in jobsTable from db
jobs Table has jobTitle, jobCompany, jobGovernorate, jobLocation and created_at column
And posted data from search form:
{"jobTitle":"designer","jobCompany":null,"jobGovernorate":null,"jobLocation":null,"postingDate":"ad"}
I mean some input may be null, so how to write dynamic where clause for inputs have value, i want search engine able to search by JobTitle, JobCompany or All inputs if have value.
Hint: fields name and table columns name are same
if there's a way to retrieve jobs from my db like
DB::table('jobs')->where($request->all())
Sorry for poor english, I don't know how to explain my question
I prefer to define all search fields.
$searchFields = ['jobTitle','jobCompany','jobGovernorate','jobLocation','postingDate'];
$jobQuery = DB::table('jobs');
foreach ($searchFields as $field) {
if ($request->has($field)) {
$jobQuery->where($field, $request->input($field));
}
}
$results = $jobQuery->get();
you have to code the query, I mean, what are you looking for?
something like
DB::table('jobs')->where([
['jobTitle', 'like', $request->jobTitle . '%'],
['jobCompany', 'like', $request->jobCompany . '%']])->get();

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);

eloquent or-query over pivot table

i have this 2 models
Track
id
name
artist_id
Artist
id
name
class Song extends \Eloquent{
public function artist(){
return $this->hasOne('Artist','id', 'artist_id');
}
}
class Artist extends \Eloquent{
public function songs(){
return $this->hasMany('Song', 'artist_id', 'id');
}
}
Now i want to realize a search given the search term "happy pharrel".
It is clear to me that i have to search the songs where the name of the Song is "happy" or the name of the artist is "happy" and where the name of the song is "pharrel" or the name of the artist is "pharrel".
now i'm wondering how i could do such a query with a condition to the song table and the artist table?
Your code shows that you have specified relations between your tables / classes -- this is good, but I don't think it necessarily helps in the case of a search. It's an excellent way to keep your syntax clean and also for eager loading, but you'll be better off writing a new query for search terms which need to search different columns on different tables.
I'm thinking something along these lines, inside a controller method called when a user submits his search:
$keywords = explode(' ', Input::get('search'));
$results = Song::join('artists', 'songs.artist_id', '=', 'artists.id')
->whereIn('artists.name', $keywords)
->orWhereIn('songs.name', $keywords)
->get();
It's fairly simplistic, but should be enough to get you started.
as tbuteler answered it's the quickest way to get the results to to a database query.
foreach($keywords as $p){
$songs->where(function($query) use($p){
$query->where('artists.name',"like", "%".$p."%")
->orWhere('songs.name', "like", "%".$p."%");
});
}
if you dont do the where(function($query){...} there is 1 query with many or's but and connection between each "or" part is missing
maybe that helps somebody else later

How to 'order_by' on second table when using eloquent one-to-many

Of course I can use order_by with columns in my first table but not with columns on second table because results are partial.
If I use 'join' everything works perfect but I need to achieve this in eloquent. Am I doing something wrong?
This is an example:
//with join
$data = DB::table('odt')
->join('hdt', 'odt.id', '=', 'hdt.odt_id')
->order_by('hdt.servicio')
->get(array('odt.odt as odt','hdt.servicio as servicio'));
foreach($data as $v){
echo $v->odt.' - '.$v->servicio.'<br>';
}
echo '<br><br>';
//with eloquent
$data = Odt::get();
foreach($data as $odt){
foreach($odt->hdt()->order_by('servicio')->get() as $hdt){
echo $odt->odt.' - '.$hdt->servicio.'<br>';
}
}
In your model you will need to explicitly tell the relation to sort by that field.
So in your odt model add this:
public function hdt() {
return $this->has_many('hdt')->order_by('servicio', 'ASC');
}
This will allow the second table to be sorted when using this relation, and you wont need the order_by line in your Fluent join statement.
I would advise against including the order by in the relational method as codivist suggested. The method you had laid is functionally identical to codivist suggestion.
The difference between the two solutions is that in the first, you are ordering odt ( all results ) by hdt.servicio. In the second you are retrieving odt in it's natural order, then ordering each odt's contained hdt by servico.
The second solution is also much less efficient because you are making one query to pull all odt, then an additional query for each odt to pull it's hdts. Check the profiler. Considering your initial query and that you are only retrieving one column, would something like this work?
HDT::where( 'odt_id', '>', 0 )->order_by( 'servico' )->get('servico');
Now I see it was something simple! I have to do the query on the second table and get contents of the first table using the function odt() witch establish the relation "belongs_to"
//solution
$data = Hdt::order_by('servicio')->get();
foreach($data as $hdt){
echo $hdt->odt->odt.' - '.$hdt->servicio.'<br>';
}
The simple answer is:
$data = Odt::join('hdt', 'odt.id', '=', 'hdt.odt_id')
->order_by('hdt.servicio')
->get(array('odt.odt as odt','hdt.servicio as servicio'));
Anything you can do with Fluent you can also do with Eloquent. If your goal is to retrieve hdts with their odts tho, I would recommend the inverse query for improved readability:
$data = Hdt::join('odt', 'odt.id', '=', 'hdt.odt_id')
->order_by('hdt.servicio')
->get(array('hdt.servicio as servicio', 'odt.odt as odt'));
Both of these do exactly the same.
To explain why this works:
Whenever you call static methods like Posts::where(...), Eloquent will return a Fluent query for you, exactly the same as DB::table('posts')->where(...). This gives you flexibility to build whichever queries you like. Here's an example:
// Retrieves last 10 posts by Johnny within Laravel category
$posts = Posts::join('authors', 'authors.id', '=', 'posts.author_id')
->join('categories', 'categories.id', '=', 'posts.category_id')
->where('authors.username', '=', 'johnny')
->where('categories.name', '=', 'laravel')
->order_by('posts.created_at', 'DESC')
->take(10)
->get('posts.*');

Categories