Trying to join tables in laravel without join elqouent query - php

here is the code That joins two tables users(id,last_name,firstname) barbers(id,id_user) avis(id,rating,id_user) now my problem is that i'm trying to join between tables without using join I want another way
$users = User::select('barbers.*','users.*')
->join('barbers', 'barbers.id_user', '=', 'users.id')
->join('avis','avis.id_barber','=','barbers.id')
->whereHas('commandes', function ($query) use ($searchTermes1) {
$query->where('barbers.id', '>', 0)
->havingRaw('count(*) >= ?', [(int)$searchTermes1]);
})
->whereIn('barbers.id_state', [1, 4])
->where('isValidate', true)
->where(function ($query) use ($searchTerm) {
$query->where('barbers.name_barber', 'like', '%'.$searchTerm.'%')
->orWhereRaw("concat(first_name, ' ', last_name) like '%$searchTerm%'")
->orWhereRaw("concat(last_name, ' ', first_name) like '%$searchTerm%'");
})
->orderBy('barbers.created_at', 'desc')
->paginate(10);

I'm not a Laravel guy, but it looks from a little searching like you could do something like this:
Model::select(DB::raw('your-raw-join-query-here'))->get();
That would allow you to run raw SQL directly, if you really need to. Hopefully someone else will have a more elegant answer.

Related

How to join tables with more than one attribute match?

I am trying to turn my raw sql into laravel query builder and I encounter difficulty on how to join multiple tables using with many attributes match.
In this case, I want to join the table jr_h and jr_d with three attributes match (book,p_seq and staff_code) rather than one (book).
Raw sql:
$sql = "select from_time,to_time,t.staff_code,s.name_t as staff_name,t.book,t.p_code,t.p_seq,p.hrs1,s.img_file,
t.hrs_work,p.sharing_cnt as hrs_work, t.hrs_ot as hrs_ot from jr_d as t
inner join jr_h as p on(t.book=p.book and t.p_seq=p.p_seq and t.staff_code=p.staff_code)
inner join astaff as s on(t.staff_code=s.staff_code) ";
Laravel query builder:
$jr_d = DB::table('jr_d')
->join('jr_h', 'jr_d.book', '=', 'jr_h.book')
->join('astaff', 'jr_d.staff_code', '=', 'astaff.staff_code')
->select('jr_h.*','jr_d.*','astaff.*','astaff.name_t as staff_name')
->where('jr_d.ref_group','=','E')
->get();
and also want to know if there is a way to make the query faster since it has a lot of data in the tables.
Laravel joins with multiple conditions:
$results = DB::table('jr_d')
->select('jr_h.*','jr_d.*','astaff.*','astaff.name_t as staff_name')
->join('jr_h', 'jr_d.book', '=', 'jr_h.book')
->join('jr_h as p', function($query){
$query->on('t.book','=', p.book');
$query->on('t.p_seq','=', 'p.p_seq');
$query->on('t.staff_code', '=', 'p.staff_code');
})
->where('jr_d.ref_group','=','E')
->get();
`
Try this:
// ...
->join('jr_h p', function($join) {
$join->on('t.book', '=', 'p.book');
$join->on('t.p_seq', '=', 'p.p_seq');
// ... more conditions
});
Try this.
$jr_d = DB::table('jr_d')
->join('jr_h', 'jr_d.book', '=', 'jr_h.book')
->join('astaff', 'jr_d.staff_code', '=', 'astaff.staff_code')
->select('*','astaff.name_t as staff_name')
->where('jr_d.ref_group','=','E')
->get();

If using a query builder as to what in the form of its laravel?

I have a query sql like the following may be a bit complex, I am a bit of trouble to convert into a for framework laravel. Please help for everything with framework laravel query results. My problem here is, I do not know how to create a sub select query to laravel framework. Thanks guys.
SELECT
lin_users.status_employee_id,
lin_users.id,
lin_users.username,
lin_users.created,
lin_users.modified,
lin_employee_attributes.unit_code,
lin_employee_attributes.position_code,
lin_employee_attributes.begin_date,
lin_employee_attributes.end_date,
contactnumber.contact_id as phone_number,
contactmobile.contact_id as cell_number,
contactemail.contact_id as email
FROM lin_users
INNER JOIN lin_status_employees
ON lin_users.status_employee_id = lin_status_employees.id
INNER JOIN lin_people
ON lin_status_employees.person_id = lin_people.id
INNER JOIN lin_employee_attributes
ON lin_users.status_employee_id = lin_employee_attributes.status_employee_id
LEFT JOIN lin_contacts AS contactnumber
ON lin_people.id = contactnumber.person_id AND contactnumber.contact_type = 'Work Telephone'
LEFT JOIN lin_contacts AS contactmobile
ON lin_people.id = contactmobile.person_id AND contactmobile.contact_type = 'Mobile'
LEFT JOIN lin_contacts AS contactemail
ON lin_people.id = contactemail.person_id AND contactemail.contact_type = 'Email'
WHERE lin_employee_attributes.begin_date = '2016-11-07'
OR lin_employee_attributes.end_date = '2017-10-21'
GROUP BY lin_users.id,
lin_employee_attributes.unit_code,
lin_employee_attributes.position_code,
lin_employee_attributes.begin_date,
lin_employee_attributes.end_date, lin_people.id,
contactnumber.contact_id,
contactmobile.contact_id,
contactemail.contact_id;
Try this:
const TABLE = 'my_table_name';
return $this
->select(
self::TABLE . 'id as myidalias',
self::TABLE . 'username as myuseralias')
->addSelect(DB::raw(
"
(your custom select here) as mycustomresult
"
));
You can add as many addSelect as you want. Also when you have a lot of complex queries like this, a lot of times you have duplicated parts on them so I highly recommend using scopes it makes your code clean and reusable.
public function scopeLeftJoinCategory($query)
{
return $query
->leftJoin(Category::CONTENTS_CATEGORIES . ' AS cc', 'con.id', '=', 'cc.content_id')
->leftJoin(Category::TABLE . ' AS cat', 'cc.category_id', '=', 'cat.id');
}
Then you just use it like this: ->leftJoinCategory()
Using this work. Finally, with the above query can be solved with the concept query to query in laravel.
$users = $this->db->getTable('users')
->select('users.status_employee_id',
'users.id',
'users.username',
'users.email',
'users.created',
'users.modified',
'users.flag_delete',
'employee_attributes.unit_code',
'employee_attributes.position_code',
'employee_attributes.begin_date',
'employee_attributes.end_date',
'contactnumber.contact_id as phone_number',
'contactmobile.contact_id as cell_number',
'contactemail.contact_id as email'
)
->join('status_employees', 'users.status_employee_id', '=', 'status_employees.id')
->join('people', 'status_employees.person_id', '=', 'people.id')
->join('employee_attributes', 'users.status_employee_id', '=', 'employee_attributes.status_employee_id')
->leftJoin('contacts AS contactnumber', function($join)
{
$join->on('people.id', '=', 'contactnumber.person_id');
$join->on('contactnumber.contact_type','=', DB::raw("'Work Telephone'"));
})
->leftJoin('contacts AS contactmobile', function($join)
{
$join->on('people.id', '=', 'contactmobile.person_id');
$join->on('contactmobile.contact_type','=', DB::raw("'Mobile'"));
})
->leftJoin('contacts AS contactemail', function($join)
{
$join->on('people.id', '=', 'contactemail.person_id');
$join->on('contactemail.contact_type','=', DB::raw("'Email'"));
})
->where(function ($query) use ($begin_date, $end_date) {
$query->where('employee_attributes.begin_date', $begin_date)
->orWhere('employee_attributes.end_date', $end_date);
})
->groupby('users.status_employee_id',
'users.id',
'users.username',
'users.email',
'users.created',
'users.modified',
'users.flag_delete',
'employee_attributes.unit_code',
'employee_attributes.position_code',
'employee_attributes.begin_date',
'employee_attributes.end_date',
'contactnumber.contact_id',
'contactmobile.contact_id',
'contactemail.contact_id'
)
->get();

Laravel Eloquent - Select MAX with other columns

I'm trying to select a number of columns along with MAX. The raw query would be something like: SELECT users.id, ..., MAX(ur.rank) AS rank but I cannot figure out how to do it using the query builder supplied by Laravel in Eloquent.
This is my attempt:
$user = User::join('users_ranks AS ur', function($join) {
$join ->on('ur.uid', '=', 'users.id');
})
->where('users.id', '=', 7)
->groupBy('users.id')
->first(['users.id', 'users.username', 'MAX(ur.rank) AS rank']);
I simply cannot figure it out. What I want to achieve is I'm selecting a user where users.id = 7, and I'm wanting to select the MAX rank that's in users_ranks where their users_ranks.uid = users.id.
I was told to avoid sub-queries as when working with large result sets, it can slow things down dramatically.
Can anyone point me in the right direction? Thanks.
I think you should rewrite it like this:
DB::table('users')
->select(['users.id', 'users.username', DB::raw('MAX(ur.rank) AS rank')])
->leftJoin('users_ranks AS ur', 'ur.uid', '=', 'users.id')
->where('users.id', '=', 7)
->groupBy('users.id')
->first();
No sense to use User:: if you use table names later and want to fetch not all of the fields ( 'users.id', 'users.username' ).

Eloquent - join clause with string value rather than column heading

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'")

Search in multiple tables by eloquent query

I have two tables: posts and pages. Based on the keyword, I want to search different columns of the two tables for the occurrence of keyword. The two tables do not have related content.
I have written two queries one for each table. Following are the queries:
$result1 = Post::where('title_en', 'LIKE', '%' . $keyword . '%')
->or_where('title_np', 'LIKE', '%' . $keyword . '%')
->order_by('id', 'desc')
->paginate(10);
$result2 = Page::where('title', 'LIKE', '%' . $keyword . '%')
->or_where('content', 'LIKE', '%' . $keyword . '%')
->order_by('id', 'desc')
->paginate(10);
The above queries return two different Laravel\Paginator object. But I want a single Laravel\Paginator object so that a single pagination is displayed on the page which works for both the queries or on a single query which achieves the functionality of both the above queries. How would I be able to do that?
Since they are unrelated tables, you need to do some trickery that's simply too complex for Eloquent to handle, you need to do something similar to the following to join the two queries together, and still be able to do your limit / ordering on the combined queries:
$results = DB::query('SELECT id, title FROM (
SELECT id, title FROM `post` where `title_np` LIKE "%'.$keyword.'%" OR `title_en` LIKE "%'.$keyword.'%"
UNION ALL
SELECT id, title FROM `page` where `title` LIKE "%'.$keyword.'%" OR `content` LIKE "%'.$keyword.'%"
) temp_table
ORDER BY `id` desc
LIMIT 0, 10
')
NB the above is untested, purely an example of the approach you'll need to take, not sure this will actually work.
I know this question has been answered ages ago but If someone ends up here like me, I had a very similar issue, and here is how I did it using the eloquent way :
$users = User::where('active', 1)
->where(function ($subQuery) use ($searchKeyword) {
$subQuery->where('pseudo', 'LIKE', "%$searchKeyword%")
->orWhere('first_name', 'LIKE', "%$searchKeyword%")
->orWhere('last_name', 'LIKE', "%$searchKeyword%")
->orWhere('email', 'LIKE', "%$searchKeyword%");
})
->whereHas('addressPrincipal')
->select(array_merge(['id', 'pseudo', DB::raw("CONCAT(users.first_name,' ',users.last_name) as name")],
[DB::raw('"user" as source')]));
$usersAll = Subsidiary::where('active', 1)
->where(function ($subQuery) use ($searchKeyword) {
$subQuery->where('slug', 'LIKE', "%$searchKeyword%")
->orWhere('name', 'LIKE', "%$searchKeyword%")
->orWhere('email_principal', 'LIKE', "%$searchKeyword%");
})
->unionAll($users)
->select(array_merge(['id', 'slug as pseduo', 'name'],
[DB::raw('"subsidiary" as source')]))
->paginate(10);
You must have noticed that I have used array_merge in the select statement, I have done this as I needed to know from which table respective records were getting fetched.

Categories