How to use inner joins with subqueries in Laravel Eloquent - php

Note: this is laravel 5.3
Basically I'm running a query when a user selects arabic translation.. the full sql looks like this
select s.ref, t.text as ref_ar
FROM stores AS s
INNER JOIN
(SELECT item, text
FROM translator_translations
WHERE locale ='ar'
AND namespace ='*'
AND item like 'store.ref%'
) AS t
ON substring(s.ref_translation from 14 for 26) = t.item;
don't see much documentation on subqueries on the official Laravel docs (there are inner join stuff but not good enough) and the SO advice seems extra-hacky.. advice?
context
this will be used as a scope inside a model, so this works for example:
public function scopeFilterLanguage($query, $language_id)
{
if (!$language_id || intval($language_id) != LanguageConstants::ARABIC_LANGUAGE_ID) {
return $query;
}
return $query->whereRaw("
substring(ref_translation from 14 for 26) in
(select item
from
translator_translations
where
locale ='ar' and namespace ='*'
and
item like 'store.ref%')");
}
but it doesn't give me what i want. (ie i have to use the bigger version at the start of this post)

this worked (ignore the dynamic stuff like this->getClassName etc).. the basic logic works just fine
public function scopeAddTranslations($query)
{
$t = new Translation();
$subq = $t->select('item','text as ref_ar')
->where('locale','=','ar')
->where('item','like',$this->getClassName().'.ref%');
$query->leftjoin(\DB::raw('('.$subq->toSql().') as t'),
function ($join) use ($subq) {
$join->on(\DB::raw('SUBSTRING('.$this->getTable().'.ref_translation
FROM 14 FOR 26)'),
'=',
\DB::raw('t.item'))
->addBinding($subq->getBindings());
});
return $query;
}

Here's my completely untested and best guess effort.
public function scopeFilterLanguage($query, $language_id)
{
if (!$language_id || intval($language_id) != LanguageConstants::ARABIC_LANGUAGE_ID) {
return $query;
}
return $query->join('translator_translations', function($join) {
$join->selectSub(function($q) {
$q->where('t.locale' => 'ar')
$q->where('t.namespace', '*')
$q->where('t.item', 'like', $this->ref . '%')
}, 't');
})->on('t.item', '=', substr($this->ref_translation, 14, 26))
->select('t.text', 'ref');
}

Related

laravel eloquent complex select inside where statement

halo, i have data and want to display it like picture below
there are two models relationship, Person and Installment.
this is Person model:
class Person extends Model
{
protected $table = 'person';
public function angsuran()
{
return $this->hasMany(Installment::class);
}
}
this is Installment model:
class Installment extends Model
{
protected $table = 'installment';
public function person()
{
return $this->belongsTo(Person::class);
}
}
and this is my controller to querying and display data
$data = Person::with('angsuran')
->whereHas('angsuran', function ($q) {
$q->whereBetween('installment_date', [\DB::raw('CURDATE()'), \DB::raw('CURDATE() + INTERVAL 7 DAY')])
->where('installment_date', '=', function () use ($q) {
$q->select('installment_date')
->where('status', 'UNPAID')
->orderBy('installment_date', 'ASC')
->first();
});
});
return $data->get();
it show error unknow colum person.id in where clause
please help. thanks.
As the comment said, you need to put $q as a parameter to the Closure.
When using subqueries, it's useful to tell the query builder which table it is supposed to query from.
I've rewritten your query. It should achieve what you're looking for. Also, changed the CURDATE to Carbon objects.
today() returns a datetime to today at 00:00:00 hours. If you need the hours, minutes and seconds, replace today() by now().
$data = Person::with('angsuran')
->whereHas('angsuran', function ($subquery1) {
$subquery1->where('installment_date', function ($subquery2) {
$subquery2->from('installment')
->select('created_at')
->where('status', 'UNPAID')
->whereBetween('installment_date', [today(), today()->addWeeks(1)])
->orderBy('installment_date')
->limit(1);
});
});
Using with and whereHas you will end up with two query even if you have limit(1) in your subQuery and the result will show all 4 installment related to the person model. also I don't think you can order on the subquery, it should be before the ->get
so here's i've rewritten your code
$callback = function($query) {
$query->whereBetween('installment_date', [today(), today()->addDays(7)])
->where('status', 'UNPAID')
->orderBy('installment_date');
};
$data = Person::whereHas('angsuran', $callback)->with(['angsuran' => $callback])->get();
or you can use query scope. please see this answer Merge 'with' and 'whereHas' in Laravel 5

laravel raw join query

I have a function that accepts raw where conditions and joins:
query('data',['fieldA','fieldB'], 'fieldA > 10 AND fieldB < 20', 'LEFT JOIN users ON data.user_id = users.id');
function query($table, $keys = [], $where = '', $joins = '') {
$query = DB::table($table)->select($keys);
if(!empty($where)) {
$query=$query->whereRaw($where);
}
if(!empty($joins)) {
$query=$query->?????????????
}
return $query->get();
}
How do I use the raw join with the query builder the way I can use whereRaw for the where condition?
Haven't good smell but works
\DB::table('data')->join('user', function($join){
$join->on(\DB::raw('( `data`.`user_id` = `user.id` or (`data`.`user_id` is null and `data`.`other_field` is null)) and 1 '),'=',\DB::raw('1'));
})
Don't bother with the query builder if you're just using raw expressions on everything.
Option 1: Utilize PDO
PDO is the underlying driver used by Laravel. To get the PDO object, run:
$pdo = DB::connection()->getPdo();
Option 2: Run raw queries
You can run entire selects through Laravel without "building" a query:
DB::select("SELECT * FROM table WHERE ..");
This even allows parameter binding when you need it.
https://laravel.com/docs/5.5/database
Here I have put some idea how can you make your method little bit generic. Do same thing for where clause and other part of the query.
query('data',['fieldA','fieldB'], 'fieldA > 10 AND fieldB < 20', 'LEFT', 'users', 'data.user_id','users.id');
function query($table, $keys = [], $where = '', $join_type = 'LEFT', $join_table='', $join_field1='', $join_field2='') {
$query = DB::table($table)->select($keys);
if(!empty($where)) {
$query=$query->whereRaw($where);
}
if(!empty($joins)&&!empty($join_type)&&$join_type=='LEFT') {
$query=$query->leftJoin($join_table, $join_field1, '=', $join_field2)
}
if(!empty($joins)&&!empty($join_type)&&$join_type=='INNER') {
$query=$query->join($join_table, $join_field1, '=', $join_field2)
}
///and so on
return $query->get();
}
//But you can make this method more generic, I just put some idea so that you can make this method more flexible
//I did not take a look at your other part of the method though.
Note: I did not put multiple joins only two table joins but you can make your method more generic form and more flexible. I just tried to put some idea that comes into my mind. If I am wrong then correct me please.
Reference:
Laravel - Joins
DB::table('data')->join('users','data.user_id','users.id')->where(~~~)

How to fetch users not assigned to a particular role in Laravel [duplicate]

In Laravel we can setup relationships like so:
class User {
public function items()
{
return $this->belongsToMany('Item');
}
}
Allowing us to to get all items in a pivot table for a user:
Auth::user()->items();
However what if I want to get the opposite of that. And get all items the user DOES NOT have yet. So NOT in the pivot table.
Is there a simple way to do this?
Looking at the source code of the class Illuminate\Database\Eloquent\Builder, we have two methods in Laravel that does this: whereDoesntHave (opposite of whereHas) and doesntHave (opposite of has)
// SELECT * FROM users WHERE ((SELECT count(*) FROM roles WHERE user.role_id = roles.id AND id = 1) < 1) AND ...
User::whereDoesntHave('Role', function ($query) use($id) {
$query->whereId($id);
})
->get();
this works correctly for me!
For simple "Where not exists relationship", use this:
User::doesntHave('Role')->get();
Sorry, do not understand English. I used the google translator.
For simplicity and symmetry you could create a new method in the User model:
// User model
public function availableItems()
{
$ids = \DB::table('item_user')->where('user_id', '=', $this->id)->lists('user_id');
return \Item::whereNotIn('id', $ids)->get();
}
To use call:
Auth::user()->availableItems();
It's not that simple but usually the most efficient way is to use a subquery.
$items = Item::whereNotIn('id', function ($query) use ($user_id)
{
$query->select('item_id')
->table('item_user')
->where('user_id', '=', $user_id);
})
->get();
If this was something I did often I would add it as a scope method to the Item model.
class Item extends Eloquent {
public function scopeWhereNotRelatedToUser($query, $user_id)
{
$query->whereNotIn('id', function ($query) use ($user_id)
{
$query->select('item_id')
->table('item_user')
->where('user_id', '=', $user_id);
});
}
}
Then use that later like this.
$items = Item::whereNotRelatedToUser($user_id)->get();
How about left join?
Assuming the tables are users, items and item_user find all items not associated with the user 123:
DB::table('items')->leftJoin(
'item_user', function ($join) {
$join->on('items.id', '=', 'item_user.item_id')
->where('item_user.user_id', '=', 123);
})
->whereNull('item_user.item_id')
->get();
this should work for you
$someuser = Auth::user();
$someusers_items = $someuser->related()->lists('item_id');
$all_items = Item::all()->lists('id');
$someuser_doesnt_have_items = array_diff($all_items, $someusers_items);
Ended up writing a scope for this like so:
public function scopeAvail($query)
{
return $query->join('item_user', 'items.id', '<>', 'item_user.item_id')->where('item_user.user_id', Auth::user()->id);
}
And then call:
Items::avail()->get();
Works for now, but a bit messy. Would like to see something with a keyword like not:
Auth::user()->itemsNot();
Basically Eloquent is running the above query anyway, except with a = instead of a <>.
Maybe you can use:
DB::table('users')
->whereExists(function($query)
{
$query->select(DB::raw(1))
->from('orders')
->whereRaw('orders.user_id = users.id');
})
->get();
Source: http://laravel.com/docs/4.2/queries#advanced-wheres
This code brings the items that have no relationship with the user.
$items = $this->item->whereDoesntHave('users')->get();

Limit result per category with Laravel 4.2 MySQL query

I've to build a research system for an announcements website. We can search through categories or via the announcement city.
When someone research something I want to set a limit of results per category (example : 3) using Eloquent.
I know this isn't easy at all, even in raw SQL, and it's been hours i'm trying to find a way without success. I tried to add a closure in the query but it's very hard for me to understand how to use that properly ...
I understood i needed to make a subquery to do the trick, but it's also tricky to know how to organize all this.
The workbench (followed by the current query which isn't working) :
Here's the controller with the query :
$announcements = Announcement::select('announcements.*')
->withCitySlug($location)
->withCategory($category_id)
->perCategoryLimit(3)
->get();
The model Announcement (the interesting part) :
/**
* HasManyThrough
*/
public function categories()
{
return $this->belongsToMany('Category', 'announcement_categories');
}
public function scopeWithCitySlug($query, $city_slug) {
if (empty($city_slug)) return $query;
return $query->where('city_slug', 'LIKE', '%'.$city_slug.'%');
}
public function scopeWithCategory($query, $category_id) {
if ($category_id === FALSE) return $query;
return $query->join('announcement_categories', 'announcement_categories.announcement_id', '=', 'announcements.id')
->join('categories', 'categories.id', '=', 'announcement_categories.category_id') ->where('categories.id', '=', $category_id);
}
public function scopePerCategoryLimit($query, $limit) {
return $query;
/*return $query->with(array('categories' => function($q)
{
$q->limit(3)->get();
}));*/
}
Any Eloquent/SQL expert around here ? A little help in the way to solve this would be perfect ;)
PS : If i didn't give enough code to understand the problem, just let me know !
Well, you can select all categories and use an foreach with a limit to get all results or use partition by from sql.

trying to Join 2 table query in Fluent laravel 4

Im trying to Joing 2 table in Fluent trough my Model i run the query on mysql client and give me the return i want.
this is the standard query
select `songlist`.*, `queuelist`.* from `songlist` inner join `queuelist` on `songlist`.`id` = `queuelist`.`songID` where `queuelist`.`songID` = songlist.ID and `songlist`.`songtype` = 'S' and `songlist`.`artist` <> "" order by `queuelist`.`sortID` ASC limit 4
it does return the data im looking for.
now on my model using fluent.
i did like this.
public static function comingUp()
{
$getcomingUp = DB::table('songlist')
->join('queuelist', 'songlist.id', '=', 'queuelist.songID')
->select('songlist.*','queuelist.*')
->where('queuelist.songID', '=', 'songlist.ID')
->where('songlist.songtype', '=', 'S')
->where('songlist.artist', '<>', '')
->orderBy('queuelist.sortID', 'ASC')
->take('4')
->get();
return $getcomingUp;
}
and my controller to test if i get the data look like this
public function getComingUp()
{
$getcomingUp = Radio::comingUp();
foreach ($getcomingUp as $cup)
{
echo $cup->title;
}
// return View::make('comingup', compact('comingup'));
}
as you can see the foreach is no returning any data there is nothing wrong with the query because laravel give me no error at all. but i cant just get the foreach to display the data im looking for.
i try with $cup->songlist.title;
and it dont work ether.
Thanks any help will be appretiated. againg sorry for my English.
You can do something like this.
public static function comingUp()
{
$getcomingUp = DB::table('songlist')
->select('songlist.*','queuelist.*')
->join('queuelist', 'queuelist.songID', '=', 'songlist.id')
->where('songlist.songtype', '=', 'S')
->where('songlist.artist', '<>', '')
->orderBy('queuelist.sortID', 'ASC')
->take('4')
->get();
return $getcomingUp;
}

Categories