Laravel Eloquent query for join with like - mysql

I have this raw query but I'm struggling to convert it to eloquent. Below is my raw sql. I cannot use DB:select because i'm using paginate at the end.
select * from orders
join users on orders.user_id = users.id
where orders.id = $search
or orders.reference_no like '%$search%'
or users.name like '%$search%'
public function customer()
{
return $this->belongsTo('App\User', 'user_id', 'id');
}
$orders = Order::where('reference_no', 'LIKE', "%$search%")
->orWhere('reference_no',$search)
->orWhere('id',$search)
->whereHas('customer', function ($query) use ($search) {
$query->where('name', 'like', '%$search%');
})
->paginate(10);

Try this
$result = Order::select('orders.*')
->join('users', 'orders.user_id', '=', 'user.users.id')
->where(function($q) {
$q->where('orders.id', $search)
->orWhere('orders.reference_no', 'like', "%$search%")
->orWhere('users.name', 'like', "%$search%") ;
})
->get();

Thanks Pavel and Unai. Based on your answer manage to do this. Need to do a 'use' and in te orWhere I need to concat '%' to the actual $search variable. If I dont have concat '.' literal search is shown in the query
$orders = Order::select('orders.*')
->join('users', 'orders.user_id', '=', 'users.id')
->where(function($q) use ($search) {
$q->where('orders.id', $search)
->orWhere('orders.reference_no', 'like', '%' . $search . '%')
->orWhere('users.name', 'like', '%' . $search .'%') ;
})
->paginate(10);

Try this
$result = Order::select('orders.*')
->join('users', 'orders.user_id', '=', 'user.users.id')
->where(function($q) use ($search){
$q->where('orders.id', $search)
->orWhere('orders.reference_no','like', '%$search%')
->orWhere('users.name','like', '%$search%') ;
})
->get();

Related

laravel eloquent where and multiple or where

I'm using the Laravel Eloquent query builder and i want to have advance queries inside when clause
my eloquent :
bank::where('shop_id', $shopId)
->when(($search != ""), function ($query) use ($search) {
return $query->orWhere('bank_name', 'like', '%'.$search.'%')
->orWhere('account_name', 'like', '%'.$search.'%')
->orWhere('account_number', 'like', '%'.$search.'%');
})->toSql();
sql from eloquent :
select * from bank
where shop_id = 1
and bank_name like '%Bank%' or
account_name like '%Bank%' or
account_number like '%Bank%'
sql result that i want:
select * from bank
where shop_id = '1'
and (bank_name like '%Bank%' or
account_name like '%Bank%' or
account_number like '%Bank%')
i can use subquery but its not efficient.
You need to use the closure form of where around the or wheres:
bank::where('shop_id', $shopId)
->when(($search != ""), function ($query) use ($search) {
return $query->where(function ($query) use ($search) {
return $query
->orWhere('bank_name', 'like', '%'.$search.'%')
->orWhere('account_name', 'like', '%'.$search.'%')
->orWhere('account_number', 'like', '%'.$search.'%');
})
})
->toSql();

Laravel 8 How to join 2 tables and check if a value exists

I'm having trouble in querying 2 tables.
Basically I have a 'black_list' table with 2 columns 'user_id' and 'block_id', where 'user_id' is the current user and 'block_id' is the blocked user. The other table is 'users' where there are the information of the registered users.
In my site I have a page where users are searched, my problem is that if id1 blocked id2, when id2 searches id1 it should not be displayed, so in the table 'black_list' I will have these values ​​user_id = 1 and block_list = 2
I've tried so many ways, but I'm not succeeding, can you help me? Excuse my English
public function search(Request $request){
$id= Auth::id();
$query = $request->query('query');
$utentis = DB::table('black_lists')
->join('users', 'users.id', '=', 'users.id')
->where('users.id', '!=', $id)
->where('users.name', 'like', '%' . $query . '%')
->where('black_lists.user_id', '!=', 'users.id')
->orWhere('users.cognome', 'like', '%' . $query . '%')
->where('black_lists.user_id', '!=', 'users.id')
->where('users.id', '!=', $id)
->orWhere('users.username', 'like', '%' . $query . '%')
->where('black_lists.user_id', '!=', 'users.id')
->where('users.id', '!=', $id)
->select('users.id', 'users.name', 'users.fotoProfilo')
->get();
if ($utentis->count() > 0) {
return response()->json($utentis);
}
}
I assume you create a many-to-many relationship between users and black_list is a pivot table.
public function search(Request $request)
{
$id = $request->id;
return User::where('id', $id)
->whereDoesntHave('blocks', function($query) use ($id) {
$query->where('user_id', '!=', $id);
}),
]);
}
UPDATE
// User.php
public function blocks()
{
return $this
->belongsToMany(User::class, 'black_list', 'block_id', 'user_id')
->using(BlackList::class)
->withTimestamps();
}
Notes:
The column names may be in the wrong order because I always mix them. Look at the documentation for more info.
If you created a model for pivot table you need to add ->using(BlackList::class)
If you have BlackList.php, you need to extend it to Pivot rather than Model.
Thanks to both of you for the prompt reply. Unfortunately it returns me null with #gbalduzzi solution. I try to attach a screen of the tables.
The variable $id = Auth::id();
enter image description hereWhen I run the query, it should return me the user profile only if in the black_list table there is no user_id == "user id that blocked me" and block_id == $ id. Thanks again for your help.
Perfect works great, thanks so much for the help
public function search(Request $request)
{
$id= Auth::id();
$query = $request->query('query');
$utentis = User::where('users.id', '!=', $id)
->where(function ($filter) use ($query) {
$filter->where('users.name', 'like', '%' . $query . '%')
->orWhere('users.cognome', 'like', '%' . $query . '%')
->orWhere('users.username', 'like', '%' . $query . '%');
})
->whereDoesntHave('blocks', function ($query) use ($id) {
$query->where('black_lists.block_id','=', $id)
->where('black_lists.user_id','!=', 'users.id');
})
->select('users.id', 'users.name', 'users.fotoProfilo')
->get();
//Log::debug($utentis);
if ($utentis->count() > 0) {
return response()->json($utentis);
}
}

Query for returning individual records from related table in a polymorphic relationship

I'm currently working with an Activities table which has Thread and Replies records associated with it. When I try to join the tables, I get a mix and match and both records and it doesn't return individual records, but with records containing both Thread and Reply "body" field. I'm hoping someone can see what I'm trying to do with the code I'm providing:
if (request('name')){
$name = request('name');
$user = User::where('name', $name)->firstOrFail();
$activities = \DB::table('activities')
->leftJoin('threads', function($builder) use ($user){
$builder->on('threads.user_id', '=', 'activities.user_id')
->where('activities.user_id', '=', $user->id)
->where('activities.activity_type', '=', 'App\Thread');
})
->leftJoin('replies', function($builder) use ($user){
$builder->on('replies.user_id', '=', 'activities.user_id')
->where('activities.user_id', '=', $user->id)
->where('activities.activity_type', '=', 'App\Reply');
})
->where('replies.body', 'LIKE', '%' . $search . '%')
->orWhere('threads.title', 'LIKE', '%' . $search . '%')
->orWhere('threads.body', 'LIKE', '%' . $search . '%')
->get()->unique('id');
}
I want to return Threads and Replies separately with all the other fields, as sometimes in my experimentation it has led to the user being null or the body being null and I just don't understand why.
Sometimes it will return a App\Thread in the Activities table that I have created as an App\Reply. I'll admit my knowledge of joins is limited so I'm asking if anyone can please help!
I've got this new query here:
$activities = Activity::with('activity')->whereHas('thread', function ($query) use ($search, $user) {
$query->where('threads.user_id', '=', $user->id)
->where('threads.body', 'LIKE', '%' . $search . '%')
->orWhere('threads.title', 'LIKE', '%' . $search . '%');
})->orWhereHas('reply', function ($query) use ($search, $user) {
$query->where('replies.body', 'LIKE', '%' . $search . '%')
->where('replies.user_id', '=', $user->id);
})->get();
Thank you!
After trying to include the user in the query builder, I just added the user after my ::with clause and got the following query to work:
$activities = Activity::with('activity')->where('user_id', $user->id)->whereHas('thread', function ($query) use ($search, $user) {
$query->where('threads.body', 'LIKE', '%' . $search . '%')
->orWhere('threads.title', 'LIKE', '%' . $search . '%');
})->orWhereHas('reply', function ($query) use ($search, $user) {
$query->where('replies.body', 'LIKE', '%' . $search . '%')
->where('replies.user_id', '=', $user->id);
})->get();
Anyone in the future who may need some additional assistance can visit this link: https://zaengle.com/blog/using-wherehas-in-laravel-polymorphic-relations

Need to search multiple words in multiple table and display only those rows which has all the words in laravel

I have an equipment which has type, manufacturer , model etc and it has attributes which are in other tables. I have created a join condition to connect with attributes. Now, if i search for a keyword related to type, manufacturer or model, then it shows correct result. But , i also need to search by attribute. I don't know how to extend this search so that it can also fetch result on the basis of attributes which are in other tables. Another thing is if i right both manufacturer and attribute in search box in one time , then i need result of equipments which has both manufacturer and attribute. Please advise. Any help would be appreciated
Currently my code looks like this:
public function filterEquipementRecords(Request $request)
{
$equipements = Equipment::with('equip_status','equip_type','manufacturer', 'equip_model', 'equip_images', 'customer')
//These are join with different attribute tables
->selectRaw('equipment.*, Fuel.EQATTRPVAL_Value AS EQUIP_Fuel, Cab.EQATTRPVAL_Value AS EQUIP_Cab, Drive.EQATTRPVAL_Value AS EQUIP_Engine, PowerManu.EQATTRPVAL_Value AS EQUIP_Power, CabAttrib.EQATTR_YesNo AS EQUIP_CabYesNo')
// Fuel Type
->leftJoin('equipattributetypes as FuelType', function($join) {
$join->on('equipment.EQTYPE_ID', '=', 'FuelType.EQTYPE_ID')
->whereRaw("FuelType.EQATTRTYPE_Name = 'Fuel Type'");
})
->leftJoin('equipattributes as FuelAttrib', function($join) {
$join->on('equipment.EQUIP_ID', '=', 'FuelAttrib.EQUIP_ID')
->on('FuelType.EQATTRTYPE_ID', '=', 'FuelAttrib.EQATTRTYPE_ID');
})
->leftJoin('equipattributepickvalues as Fuel', function($join) {
$join->on('FuelAttrib.EQATTRPVAL_ID', '=', 'Fuel.EQATTRPVAL_ID');
})
// Cab
->leftJoin('equipattributetypes as CabType', function($join) {
$join->on('equipment.EQTYPE_ID', '=', 'CabType.EQTYPE_ID')
->whereRaw("CabType.EQATTRTYPE_Name = 'Cab'");
})
->leftJoin('equipattributes as CabAttrib', function($join) {
$join->on('equipment.EQUIP_ID', '=', 'CabAttrib.EQUIP_ID')
->on('CabType.EQATTRTYPE_ID', '=', 'CabAttrib.EQATTRTYPE_ID');
})
->leftJoin('equipattributepickvalues as Cab', function($join) {
$join->on('CabAttrib.EQATTRPVAL_ID', '=', 'Cab.EQATTRPVAL_ID');
})
// Drive
->leftJoin('equipattributetypes as DriveType', function($join) {
$join->on('equipment.EQTYPE_ID', '=', 'DriveType.EQTYPE_ID')
->whereRaw("DriveType.EQATTRTYPE_Name = 'Drive'");
})
->leftJoin('equipattributes as DriveAttrib', function($join) {
$join->on('equipment.EQUIP_ID', '=', 'DriveAttrib.EQUIP_ID')
->on('DriveType.EQATTRTYPE_ID', '=', 'DriveAttrib.EQATTRTYPE_ID');
})
->leftJoin('equipattributepickvalues as Drive', function($join) {
$join->on('DriveAttrib.EQATTRPVAL_ID', '=', 'Drive.EQATTRPVAL_ID');
})
//Power Manu
->leftJoin('equipattributetypes as PowerManuType', function($join) {
$join->on('equipment.EQTYPE_ID', '=', 'PowerManuType.EQTYPE_ID')
->whereRaw("PowerManuType.EQATTRTYPE_Name = 'Power Manu'");
})
->leftJoin('equipattributes as PowerManuAttrib', function($join) {
$join->on('equipment.EQUIP_ID', '=', 'PowerManuAttrib.EQUIP_ID')
->on('PowerManuType.EQATTRTYPE_ID', '=', 'PowerManuAttrib.EQATTRTYPE_ID');
})
->leftJoin('equipattributepickvalues as PowerManu', function($join) {
$join->on('PowerManuAttrib.EQATTRPVAL_ID', '=', 'PowerManu.EQATTRPVAL_ID');
})
// This is my query where i am searching on the basis of keyword, here i want to add attribute (which are there with joins) search also
->where(function ($query) use ($request) {
if($this->quick_search_enable){
if ($request->quick_search != "") {
$query->where('equipment.EQUIP_ID', 'like', '%' . $request->quick_search . '%')
->orWhere('EQUIP_AddedOn', 'like', '%' . $request->quick_search . '%')
->orWhere('EQUIP_Year', 'like', '%' . $request->quick_search . '%')
->orWhere('EQUIP_VendorYear', 'like', '%' . $request->quick_search . '%')
->orWhere('EQUIP_Cost', 'like', '%' . $request->quick_search . '%')
->orWhere('EQUIP_Price', 'like', '%' . $request->quick_search . '%')
->orWhere('EQUIP_EmailPrice', 'like', '%' . $request->quick_search . '%')
->orWhere('EQUIP_Size', 'like', '%' . $request->quick_search . '%')
->orWhere('EQUIP_Hours', 'like', '%' . $request->quick_search . '%')
->orWhere('EQUIP_SerialNumber', 'like', '%' . $request->quick_search . '%')
->orWhere('EQUIP_VendorEquipNumber', 'like', '%' . $request->quick_search . '%')
->orWhere('EQUIP_Length', 'like', '%' . $request->quick_search . '%')
// These are relations in equipment model
$query->orWhereHas('manufacturer', function ($query) use ($term) {
$query->where('MANU_ShortName', 'like', '%' . $term . '%');
});
$query->orWhereHas('equip_type', function ($query) use ($term) {
$query->where('EQTYPE_Desc', 'like', '%' . $term . '%');
});
$query->orWhereHas('equip_model', function ($query) use ($term) {
$query->where('EQMODEL_ModelNumber', 'like', '%' . $term . '%');
});
$query->orWhereHas('equip_status', function ($query) use ($request) {
$query->where('EQSTATUS_Name', 'like', '%' . $request->quick_search . '%');
});
}
}
});

How can I use 'AS' in my count query?

How can I use AS in my count query?
Actually i want to result like { "count":"number" } for json result. I dont know what should i call this thing?
public function firstHourTrades(){
$user_id = Auth::user()->id;
$data = DB::table('finaltrade')
->join('exchanges', 'finaltrade.exchange_id', '=', 'exchanges.id')
->where('finaltrade.user_id', $user_id)
->whereTime(DB::raw('IF(finaltrade.buy_datetime<finaltrade.sell_datetime, finaltrade.buy_datetime, finaltrade.sell_datetime) '), '>=', DB::raw('exchanges.start_time'))
->whereTime(DB::raw('IF(finaltrade.buy_datetime<finaltrade.sell_datetime, finaltrade.buy_datetime, finaltrade.sell_datetime) '), '<=', DB::raw("ADDTIME(exchanges.start_time, '1:00:00')"))
->count();
return response()->json($data);
}
You could also do a raw select and manually assign the alias:
$data = DB::table('finaltrade')
->select(DB::raw('count(*) as count'))
->join('exchanges', 'finaltrade.exchange_id', '=', 'exchanges.id')
->where('finaltrade.user_id', $user_id)
->whereTime(DB::raw('IF(finaltrade.buy_datetime<finaltrade.sell_datetime, finaltrade.buy_datetime, finaltrade.sell_datetime) '), '>=', DB::raw('exchanges.start_time'))
->whereTime(DB::raw('IF(finaltrade.buy_datetime<finaltrade.sell_datetime, finaltrade.buy_datetime, finaltrade.sell_datetime) '), '<=', DB::raw("ADDTIME(exchanges.start_time, '1:00:00')"))
->get();