I have this query wrote in Eloquent :
return TypeModel::with(['apt' => function($q) use ($id){
$q->leftJoin('build_apt', function($join) use($id){
$join->on('build_apt.id_apt', '=', 'apt.id_apt');
$join->on('build_apt.id_build', '=', DB::raw($id->id_build));
})
}])
->get()
->toJson();
Equivalent SQL :
SELECT *
FROM `apt`
LEFT JOIN `build_apt`
ON `build_apt`.`id_apt` = `apt`.`id_apt`
AND `build_apt`.`id_build` = 1
WHERE `apt`.`id_typeapt` in (1, 2, 3, 4, 5)
I have the result I need except one thing, the id given is null :
[
{"id_typeapt":1,"apt":[
{"id_apt":null,"image_apt":"apt_1.png"},
{"id_aptitude":null,"image_apt":"apt_2.png"}
]
]
How can I force it to look for the id from the table "apt" and not giving me "null" as a result?
Thanks you!
EDIT : Where clause is coming from the with
public function apt(){
return $this->hasMany(AptModel::class, 'id_typeapt', 'id_typeapt');
}
EDIT2 :
id_apt was crushed by the other id_apt with a simple rename I could retrieve the id :
return TypeModel::with(['apt' => function($q) use ($id){
$q->leftJoin('build_apt', function($join) use($id){
$join->on('build_apt.id_apt', '=', 'apt.id_apt');
$join->on('build_apt.id_build', '=', DB::raw($id->id_build));
})
}])->select(DB::raw("*, apt.id_apt as id_apt);
}])
You are using LEFT JOIN, which is what you want, however you have conditions on the joined table in the WHERE clause. This actually turns your LEFT JOIN to an INNER JOIN, since unmatched records will be filtered out by the WHERE clause.
You would need to tweak your Eloquent code in order to generate the following SQL query :
SELECT *
FROM `apt`
LEFT JOIN `build_apt`
ON `build_apt`.`id_apt` = `apt`.`id_apt`
AND `build_apt`.`id_build` = 1
AND `apt`.`id_typeapt` in (1, 2, 3, 4, 5)
Related
I am try
ing to get something like this
select * from `users`
inner join `settings`
on `users`.`id` = `settings`.`user_id`
and NOW() NOT BETWEEN quit_hour_start AND quit_hour_end
where `notification_key` != ''
and `device_type` = 'Android'
in eloquent. Does anyone try and get success to build this query in eloquent.
I know I can use \DB::select(DB::raw()); and get my result. But I want to use ie with Laravel eloquent method.
====== update comment for tried queries========
$androidUser = User::join('settings', function ($join) {
$join->on('users.id', '=', 'settings.user_id')
->where(DB::raw("'$currentTime' NOT BETWEEN quit_hour_start AND quit_hour_end"));
})
->where('notification_key', '!=', '')
->where('device_type' ,'=', 'Android')
->get();
$users = DB::table('users')
->whereNotBetween('votes', [1, 100]) // For one column
->whereRaw("? NOT BETWEEN quit_hour_start AND quit_hour_end", [$currentTime]) // Use whereRaw for two columns
->get();
https://laravel.com/docs/5.5/queries, or you can rewrite as to wheres
I have three tables: A, B & C.
Table A:
id
B_id
value
Table B:
id
C_id
company
Table C:
id
state
Now, I want to do this following query using Eloquoent relationship.
select * from A, B, C where A.B_id = B.id and B.C_id = C.id and C.state = 1
I decalred the relationships in each model and performed and following query:
A::with(['b' => function($query) {
$query->with(['C'=> function($q) {
$q->where('state', 1);
}]);
}])->get();
But, I am not getting the expected result.
What am I missing here?
When you use a with with a scope you are only filtering down the relationships, not the top model that you are querying on. You often have to do both a query and a scoped with.
Example:
A::query()
->whereHas('b.c', function ($q) {
$q->where('state', 1);
})
->with([
'b.c' => function ($q) {
$q->where('state', 1);
},
])->get();
try this:
A::join('B', 'B.id', '=', 'A.B_id')
->join('C', 'C.id', '=', 'B.C_id')
->select(...)
->where('C.state', 1)
->get();
in the select method you may specify what field you want to selec of each table, by example:
->select('A.*', 'B.company', 'C.state')
I am trying to make the following query in laravel:
SELECT a.name AS subname, a.area_id, b.name, u. id, u.lawyer_id,u.active_search,
FROM subarea a
LEFT JOIN user_subarea u ON u.subarea_id = a.id
AND u.user_id = ?
LEFT JOIN branch b ON a.area_id = b.id
The idea is to obtain the subareas and see if the search is activated by the user.
The user_subarea table might have a record that matches the id of the subarea table where the active_search is equal to 0 or 1. If it doesn't exist I would like the query to return null.
While I was able to achieve this in raw SQL when I try the same with eloquent in Laravel I am not returning any value. I have done the following:
$query = DB::table('subarea')
->join('user_subarea', function($join)
{
$value = \Auth::user()->id;
$join->on( 'subarea.id', '=', 'user_subarea.subarea_id')->where('user_subarea.user_id', '=',$value);
})
->leftJoin('branch', 'subarea.area_id', '=', 'branch.id')
->select('branch.name', 'subarea.name as subarea', 'user_subarea.active_search_lawyer', 'user_subarea.id' )
->get();
Any help will be much appreciated.
I found by myself the answer it was just to add a lefjoin in the first join. It is not in the laravel docs but works too.
$query = DB::table('subarea')
->lefjoin('user_subarea', function($join)
{
$value = \Auth::user()->id;
$join->on( 'subarea.id', '=', 'user_subarea.subarea_id')->where('user_subarea.user_id', '=',$value);
})
->leftJoin('branch', 'subarea.area_id', '=', 'branch.id')
->select('branch.name', 'subarea.name as subarea', 'user_subarea.active_search_lawyer', 'user_subarea.id' )
->get();
Try this one, If you get a problem, please comment.
$value = \Auth::user()->id;
$query = DB::table('subarea')
->where('user_subarea.user_id', '=',$value)
->leftJoin('user_subarea', 'subarea.id', '=', 'user_subarea.subarea_id')
->leftJoin('branch', 'subarea.area_id', '=', 'branch.id')
->select('subarea.name AS subname','subarea.area_id', 'branch.name', 'user_subarea.id','user_subarea.lawyer_id','user_subarea.active_search')
->get();
I am using LARAVEL 4 with MySQL back-end. I am novice to it.
I have a statement that returns records from 3 different tables as below :
$templates = Template::with('children')
->leftJoin('template_masters', function($join) {
$join->on('templates.template_master_id', '=', 'template_masters.id');
})
->leftJoin('surveyes', function($join) {
$join->on('templates.survey_id', '=', 'surveyes.id');
})
->get([
'templates.id',
'templates.survey_id',
'surveyes.title', // Here I want the IFNULL() condition e.g. IFNULL('surveyes.title','templates.title')
'templates.type',
'templates.created_at',
'template_masters.is_default'
]);
Basically this creates a query something like :
select `templates`.`id`,
`templates`.`survey_id`,
`surveyes`.`title`,
`templates`.`type`,
`templates`.`created_at`,
`template_masters`.`is_default`
from `templates`
left join `surveyes` on `templates`.`survey_id` = `surveyes`.`id`
left join `template_masters` on `templates`.`template_master_id` = `template_masters`.`id`
But I want this query like :
select `templates`.`id`,
`templates`.`survey_id`,
IFNULL(`surveyes`.`title`, `templates`.`title`),
`templates`.`type`,
`templates`.`created_at`,
`template_masters`.`is_default`
from `templates`
left join `surveyes` on `templates`.`survey_id` = `surveyes`.`id`
left join `template_masters` on `templates`.`template_master_id` = `template_masters`.`id`
In short, instead of surveyes.title, I want IFNULL(surveyes.title,templates.title).
How can I achieve this in ->GET([]) statement of given Eloquent ORM?
Thanks.
You need to use raw statement:
...
->get([
'templates.id',
'templates.survey_id',
DB::raw('IFNULL(surveyes.title,template_masters.title) as title'),
// or if you use namespace:
\DB::raw('IFNULL(surveyes.title,template_masters.title) as title'),
'templates.type',
'templates.created_at',
'template_masters.is_default'
]);
I have a question regarding join clauses in Eloquent, and whether you can join on a string value rather than a table column.
I have the code below querying a nested set joining parent/child records in a table 'destinations' via a table 'taxonomy'.
The second $join statement in the closure is the one causing an issue; Eloquent assumes this is a column, when I would actually just like to join on t1.parent_type = 'Destination' - ie, t1.parent_type should = a string value, Destination.
$result = DB::connection()
->table('destinations AS d1')
->select(array('d1.title AS level1', 'd2.title AS level2'))
->leftJoin('taxonomy AS t1', function($join) {
$join->on('t1.parent_id', '=', 'd1.id');
$join->on('t1.parent_type', '=', 'Destination');
})
->leftJoin('destinations AS d2', 'd2.id', '=', 't1.child_id')
->where('d1.slug', '=', $slug)
->get();
Is it possible to force Eloquent to do this? I've tried replacing 'Destination' with DB::raw('Destination') but this does not work either.
Thanking you kindly.
Another best way to achieve same is :
$result = DB::connection()
->table('destinations AS d1')
->select(array('d1.title AS level1', 'd2.title AS level2'))
->leftJoin('taxonomy AS t1', function($join) {
$join->on('t1.parent_id', '=', 'd1.id');
$join->where('t1.parent_type', '=', 'Destination');
})
->leftJoin('destinations AS d2', 'd2.id', '=', 't1.child_id')
->where('d1.slug', '=', $slug)
->get();
Replace your on with where
try using DB::raw("'Destination'")