Inner query with use variable - php

I am new to laravel and I am trying to retrieve data from three tables because the user enters 3 information then I use its to determine the row to check login
so I use this way but not work!
I do not know how to send variables in SQL
DB::table('members')
->join(DB::raw('(SELECT FROM members_courses_assign WHERE referenceNumber=>$coursenum,termkey=>$semester) courseA'), function($join) {
$join->on('members.externalPersonKey', '=', 'courseA.externalPersonKey');
})->join(DB::raw('(SELECT courses FROM WHERE referenceNumber=>$coursenum,termkey=>$semester) coursecc '), function($join) {
$join->on('courseA.referenceNumber', '=', 'coursecc.referenceNumber');
})
->where(['jobID' => $jobid])->get();

Try this :
->where('jobID',$jobid)->get();
Here in Laravel Documentation you can find all you need to know about query builder.

To pass variable to inner query (Anonymous functions) you have to pass it with use keyword as described in docs
$yourVariable= "";
DB::table('members')
->join(DB::raw('(SELECT FROM members_courses_assign WHERE referenceNumber=>$coursenum,termkey=>$semester) courseA'), function($join) use($yourVariable) {
$join->on('members.externalPersonKey', '=', 'courseA.externalPersonKey');
})->join(DB::raw('(SELECT courses FROM WHERE referenceNumber=>$coursenum,termkey=>$semester) coursecc '), function($join) use($yourVariable) {
$join->on('courseA.referenceNumber', '=', 'coursecc.referenceNumber');
})
->where(['jobID' => $jobid])->get();

DB::table('members')
->join('members_courses_assign', function($join) use ($coursenum, $semester) {
$join->on('members.externalPersonKey', '=', 'members_courses_assign.externalPersonKey')
->where('referenceNumber', $coursenum)
->where('termkey', $semester);
})
->join('courses', function($join) use ($coursenum, $semester) {
$join->on('members_courses_assign.referenceNumber', '=', 'courses.referenceNumber')
->where('referenceNumber', $coursenum)
->where('termkey', $semester);
})
->where('jobID', $jobid)
->get();
You can refer to Query Builder's advanced join clauses here.

Related

how to handle Multiple Orwhere in Laravel

I'm working in Laravel 5 and am using the Orwhere clausule, my code to consult is this:
$estudiantes= Usuario::
where('rol', '=', 'ESTUDIANTE')
->whereHas('perfil', function($query) use ($data){
if($data!="")
$query->Where('doc_identidad', '=' ,$data)
->orWhere('nombres','like','%'.$data.'%')
->orWhere('apellidos','like','%'.$data.'%');
dd($query);
})->get();
So, I want to filter every Usuario with rol ESTUDIANTE that works very fine, then I want to filter which of these have doc_identidad or nombres or apellidos like you see, I have a dd($query) to see the tree of the query, and I noticed that the first where uses and instead of or. This is the tree:
So, I have the next:
where1 and where2 or where3 or where4
and I want:
where1 and (where2 or where3 or where4)
so, how should I do it? thanks!
where1(a=1) and (where2(b=1) or where3(c=1) or where4(d=1))
Model::where(function ($query) {
$query->where('a', '=', 1);
})->where(function ($query) {
$query->where('b', '=', 1)
->orWhere('c', '=', 1)
->orWhere('d', '=', 1);
});

Laravel using select in Eloquent scope and query

I'm trying to clean up some code that I made.
This is the current code:
$message = Message::with('comments')
->join('users', 'messages.created_by', '=', 'users.id')
->join('team_user', 'messages.created_by', '=', 'team_user.user_id')
->join('teams', 'team_user.team_id', '=', 'teams.id')
->join('roles', 'team_user.role_id', '=', 'roles.id')
->select('messages.id', 'messages.message', DB::raw('CONCAT(users.first_name, " ", users.last_name) AS created_by_name'), DB::raw('CONCAT(roles.name, " ", teams.name) AS function'))
->findOrFail($id);
I tried to make it like this:
$message = Message::with('comments')
->join('users', 'messages.created_by', '=', 'users.id')
->withFunction()
->findOrFail($id);
So I made a scope called withFunction that looks like this:
return $query->join('team_user', 'messages.created_by', '=', 'team_user.user_id')
->join('teams', 'team_user.team_id', '=', 'teams.id')
->join('roles', 'team_user.role_id', '=', 'roles.id')->select(DB::raw('CONCAT(roles.name, " ", teams.name) AS function'));
But because I use this scope where I select specific column, I cant use the select in my query as well. I want it to look like this:
$message = Message::with('comments')
->join('users', 'messages.created_by', '=', 'users.id')
->withFunction()
->select('messages.id', 'messages.message')
->findOrFail($id);
So I specify the columns returned from the scope and from the query itself. I know I can't have 2 select's in a query, but is there any way this would be possible?
Would be great if you could just return columns in the scope to use it through the whole application.
The problem seems to come down to how get() works.
$original = $this->columns;
if (is_null($original)) {
$this->columns = $columns;
}
Get only adds the '*' to select if no other selects are defined.
You either need to explicitly call select('*') on the builder
$message = Message::with('comments')
->select('*')
->join('users', 'messages.created_by', '=', 'users.id')
->withFunction()
->select('messages.id', 'messages.message')
->findOrFail($id);
or add it in in your scope, this is an example from a 5.3 project.
public function apply(Builder $builder, Model $model)
{
if(is_null($builder->getQuery()->columns)){
$builder->addSelect('*');
}
$builder->addSelect(DB::raw('...'));
}
Look at addSelect(). When you use select(), your are overriding all the other selected columns and only selecting the one. By using addSelect() you will append the column to the selected columns rather than replace it.
So as a general rule you should call select() before calling any scopes that add columns, and those scopes should use addSelect().
Also... you actually do not need to return the $query in your scope because you are interacting with the query builder object. It kinda works like old school references (&).

selects, joins, & wheres in Laravel

I'm trying to select specific columns from two tables however when I add the ->select() method into my query, I get an error.
If I leave out the ->select() method, I get a valid resultset and everything works, but adding the select breaks it. Sadly the error reported has nothing to do with the query and is useless to me.
Here is the code that works:
$notifications = DB::table('notifications')
->join('notifications_pivot', function($join)
{
$join->on('notifications.id', '=', 'notifications_pivot.notification_id')
->where('notifications_pivot.user_id', '=', Session::get('id'))
->where('notifications_pivot.is_read', '=', 'N');
})
->get();
Now here's the code that breaks:
$notifications = DB::table('notifications')
->join('notifications_pivot', function($join)
{
$join->on('notifications.id', '=', 'notifications_pivot.notification_id')
->where('notifications_pivot.user_id', '=', Session::get('id'))
->where('notifications_pivot.is_read', '=', 'N');
})
->select(DB::raw('notifications.id, notifications.subject, notifications.message, notifications.url,
notifications.start_date, notifications.end_date, notifications.access_role_id, notifications_pivot.id,
notifcations_pivot.notification_id, notifications_pivot.user_id, notifications_pivot.is_read'))
->get();
It's times like these when I wish I could just write straight SQL and parse the query!
Any suggestions?
Take out the DB::raw() and just pass the fields you want as parameters.
If that doesn't work, the Laravel log at app/storage/logs/laravel.log may provide more insight.
$notifications = DB::table('notifications')
->join('notifications_pivot', function($join)
{
$join->on('notifications.id', '=', 'notifications_pivot.notification_id')
->where('notifications_pivot.user_id', '=', Session::get('id'))
->where('notifications_pivot.is_read', '=', 'N');
})
->select('notifications.id', 'notifications.subject', 'notifications.message', 'notifications.url', 'notifications.start_date', 'notifications.end_date', 'notifications.access_role_id', 'notifications_pivot.id', 'notifcations_pivot.notification_id', 'notifications_pivot.user_id', 'notifications_pivot.is_read')
->get();

Laravel eloquent SQL query with OR and AND with where clause

I know that sql AND can be achieved by consecutive where clauses. and OR with where(condition,'OR').
I want to choose all the messages from message table where sentTo = editor_id AND sentFrom= currentUser_id OR where sentTo = currentUser_id AND sentFrom = editor_id.
I have this query which I am trying to get the result through,
$this->data['messages'] = Message::where(function ($query) use($uId) {
$query->where('sentTo', '=', $this->data['currentUser']->id)
->orWhere('sentFrom', '=', $uId);
})
->where(function ($query) use($uId){
$query->where('sentTo', '=', $uId)
->orWhere('sentFrom', '=', $this->data['currentUser']->id);
})
->get();
How can I do this? Please advice.
I'm a bit confuse as you didn't provide parentheses to know which operator precedence you want.
Assuming you want WHERE (editor_id=$editorId AND sentFrom=$currentUserId) OR (sentTo=$currentUserId AND sentFrom=$editorId) then latest version of Laravel allows you to do:
Message::where(['editor_id' => $editorId, 'sentFrom' => $currentUserId])
->orWhere(['sentTo' => $currentUserId, 'sentFrom' => $editorId])->get();
No need to use closures.
Try this
$this->data['messages'] = Message::where(function ($query) use($uId) {
$query->where('sentTo', '=', $this->data['currentUser']->id)
->where('sentFrom', '=', $uId);
})-> orWhere(function ($query) use($uId){
$query->where('sentTo', '=', $uId)
->Where('sentFrom', '=', $this->data['currentUser']->id);
})->get();

Laravel Eloquent inner join with multiple conditions

I have a question about inner joins with multiple on values.
I did build my code like this in laravel.
public function scopeShops($query) {
return $query->join('kg_shops', function($join)
{
$join->on('kg_shops.id', '=', 'kg_feeds.shop_id');
// $join->on('kg_shops.active', '=', "1"); // WRONG
// EDITED ON 28-04-2014
$join->on('kg_shops.active', '=', DB::raw("1"));
});
}
Only problem is, it gives this outcome:
Column not found: 1054 Unknown column '1' in 'on clause' (SQL: select `kg_feeds`.* from `kg_feeds` inner join `kg_shops` on `kg_shops`.`id` = `kg_
feeds`.`shop_id` and `kg_shops`.`active` = `1`) (Bindings: array ( ))
As you can see, the multiple conditions in the join go fine, but it thinks the 1 is a column instead of a string. Is this even possible, or do I have to fix it in the where.
return $query->join('kg_shops', function($join)
{
$join->on('kg_shops.id', '=', 'kg_feeds.shop_id');
})
->select('required column names')
->where('kg_shops.active', 1)
->get();
You can see the following code to solved the problem
return $query->join('kg_shops', function($join)
{
$join->on('kg_shops.id', '=', 'kg_feeds.shop_id');
$join->where('kg_shops.active','=', 1);
});
Or another way to solved it
return $query->join('kg_shops', function($join)
{
$join->on('kg_shops.id', '=', 'kg_feeds.shop_id');
$join->on('kg_shops.active','=', DB::raw('1'));
});
//You may use this example. Might be help you...
$user = User::select("users.*","items.id as itemId","jobs.id as jobId")
->join("items","items.user_id","=","users.id")
->join("jobs",function($join){
$join->on("jobs.user_id","=","users.id")
->on("jobs.item_id","=","items.id");
})
->get();
print_r($user);
Because you did it in such a way that it thinks both are join conditions in your code given below:
public function scopeShops($query) {
return $query->join('kg_shops', function($join)
{
$join->on('kg_shops.id', '=', 'kg_feeds.shop_id');
$join->on('kg_shops.active', '=', "1");
});
}
So,you should remove the second line:
return $query->join('kg_shops', function($join)
{
$join->on('kg_shops.id', '=', 'kg_feeds.shop_id');
});
Now, you should add a where clause and it should be like this:
return $query->join('kg_shops', function($join)
{
$join->on('kg_shops.id', '=', 'kg_feeds.shop_id')->where('kg_shops.active', 1);
})->get();
You can simply add multiple conditions by adding them as where() inside the join closure
->leftJoin('table2 AS b', function($join){
$join->on('a.field1', '=', 'b.field2')
->where('b.field3', '=', true)
->where('b.field4', '=', '1');
})
More with where in (list_of_items):
$linkIds = $user->links()->pluck('id')->toArray();
$tags = Tag::query()
->join('link_tag', function (JoinClause $join) use ($linkIds) {
$joinClause = $join->on('tags.id', '=', 'link_tag.tag_id');
$joinClause->on('link_tag.link_id', 'in', $linkIds ?: [-1], 'and', true);
})
->groupBy('link_tag.tag_id')
->get();
return $tags;
Hope it helpful ;)
This is not politically correct but works
->leftJoin("players as p","n.item_id", "=", DB::raw("p.id_player and n.type='player'"))

Categories