I am creating an api to search users. I am doing this in Eloquent, and I am wondering if there is any way to create a query with Eloquent like this:
SELECT * FROM users WHERE CONCAT('first_name', ' ', 'last_name') LIKE '%searchstring%' OR email LIKE '%searchstring%';
Is there a way to do this with the Eloquent query builder?
What I would like to do is essentially this:
$users = User::where('CONCAT(first_name, " ",last_name)', 'LIKE', '%searchstring%')->orWhere('email','LIKE','%searchstring%')->orderBy($ob, $dir)->paginate($perPage);
This results in Column not found: 1054 Unknown column 'CONCAT(first_name," ",last_name)' in 'where clause'
I was able to find the answer to this question, and the solution was to use the DB::raw method around the column name.
The working solution looks like this:
$users = User::where(DB::raw('CONCAT(first_name, " ",last_name)'), 'LIKE', '%searchstring%')->orWhere('email','LIKE','%searchstring%')->orderBy($ob, $dir)->paginate($perPage);
Try this:
$users = User::where(\DB::raw('CONCAT(first_name, " ",last_name)'), 'LIKE', '%searchstring%')->orWhere('email','LIKE','%searchstring%')->orderBy($ob, $dir)->paginate($perPage);
Related
I have next code:
$properties = $properties
->selectRaw('*,'. $this->userCurrency->c_rate .' / c_rate * p_fixed_price AS
converted_p_fixed_price');
after that I want to sort by this price.
$properties = $properties->whereBetween('converted_p_fixed_price',
[$request->low_price ,$request->hight_price]
);
But in result i got Column not found: 1054
Please help, how to whereBetween that field in right way?
As referred Here :An alias can be used in a query select list to give a column a different name. You can use the alias in GROUP BY, ORDER BY, or HAVING clauses to refer to the column, Standard SQL disallows references to column aliases in a WHERE clause. This restriction is imposed because when the WHERE clause is evaluated, the column value may not yet have been determined, so you must use having instead of whereBetween.
The second part of your code can be something like this:
$properties = $properties
->having('converted_p_fixed_price', '>=', $request->low_price)
->having('converted_p_fixed_price', '<=' ,$request->hight_price);
As you can not use pagination with having clauses in Laravel, if you want to paginate results, you can use something like this:
$properties = $properties
->whereRaw($this->userCurrency->c_rate . ' / c_rate * p_fixed_price >= ' . $request->low_price)
->whereRaw($this->userCurrency->c_rate . ' / c_rate * p_fixed_price <= ' . $request->hight_price)
->paginate($page_length);
In php laravel i am using mysql / direct query which is shown as below:
$point_rewards = DB::select("select * from integral_history_listing INNER JOIN outlets ON integral_history_listing.branch_c LIKE CONCAT('%', outlets.outlet_code, '%') where outlets.merchant_id LIKE ".Auth::user()->id." ORDER BY integral_history_listing.add_time_c DESC");
I am able to use mysql query to get any related value to the outlet code using like clause... however i wish to write it using php laravel query builder like below :
$notices = DB::table('integral_history_listing')
->join('outlets', 'outlets.outlet_code', 'LIKE', 'integral_history_listing.branch_c')
->where('outlets.merchant_id', 'LIKE', Auth::user()->id)
->orderBy('integral_history_listing.add_time_c', 'desc')
->paginate(10);
I have try include concat within the "outlets.outlet_code" but getting module by zero error. I wish to know the proper way in using concat within inner join php laravel built query.
Try this code:
$notices = DB::table('integral_history_listing')
->join('outlets','integral_history_listing.branch_c' , 'LIKE', DB::RAW('CONCAT("%",outlets.outlet_code,"%")'))
->where('outlets.merchant_id', 'LIKE', Auth::user()->id)
->orderBy('integral_history_listing.add_time_c', 'desc')
->paginate(10);
i want to create simple drop-down inside html code from 2 table which they have single relationship, in my code i cant to get relationship data to concat that with other table columns. for example this is my code:
$user_accounts = UserAccountNumber::with('currencyType')->select('*', DB::raw('CONCAT("CardNumber: ", card_number) AS account_info'))
->whereUserId(Auth::user()->id)
->pluck('account_info', 'id');
this code work fine, but i want to conact some currencyType table columns with UserAccountNumber table and i cant use tableName.columnName into DB::raw()
for example:
$user_accounts = UserAccountNumber::with('currencyType')
->select(
'*',
DB::raw('CONCAT(" CardNumber: ", card_number, "CurrencyType: ", currencyType.title) AS account_info'))
->whereUserId(Auth::user()->id)
->pluck('account_info', 'id');
then i get this error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'currencyType.currency_type' in 'field list' (SQL: select *, CONCAT("AccountNumber: ",account_number, " CardNumber: ", card_number, "CurrencyType: ", currencyType.currency_type) AS account_info from `user_account_numbers` where `user_id` = 17)
currencyType method in Model:
public function currencyType()
{
return $this->belongsTo(CurrencyType::class, 'currency_type', 'id');
}
Laravel does not use JOINs to do relationships, so you would have to write a specific query for that. Use query builder for that.
Something like this should work:
$user_accounts = DB::table('user_account_numbers')
->join('currencyType', 'user_account_numbers.currency_id', '=', 'currencyType.id')
->select('*', DB::raw('CONCAT(" CardNumber: ", card_number, "CurrencyType: ", currencyType.title) AS account_info'))
->whereUserId(Auth::user()->id)
->get();
I hope you get the idea and can adapt it to suit your database schema.
I'm trying to fetch following things from the database:
user name
user avatar_name
user avatar_filetype
complete conversation_messages
with the following query:
static public function getConversation($id)
{
$conversation = DB::table('conversation_messages')
->where('belongsTo', $id)
->join('users', 'conversation_messages.sender', '=', 'users.id')
->join('user_avatars', 'conversation_messages.sender', '=', 'user_avatars.id')
->select('users.name', 'conversation_messages.*', 'user_avatars.name', 'user_avatars.filetype')
->get();
return $conversation;
}
It works fine so far, but the avatar's column name is 'name' like the column name from the 'users' table.
So if I'm using this query the to get the output via $conversation->name, the avatar.name overwrites the users.name
Is there a way to rename the query output like the mysql "as" feature at laravel 5.1?
For example:
$conversation->avatarName
$conversation->userName
Meh okay.. i've found a simple solution here
->select('users.name as userName', 'conversation_messages.*', 'user_avatars.name as avatarName', 'user_avatars.filetype')
As you can mention I've added the requested "as-Feature" next to the table.columnName
Take a look at this example of trying to join three tables staffs, customers and bookings(pivot table).
$bookings = \DB::table('bookings')
->join('staffs', 'staffs.id' , '=', 'bookings.staff_id')
->join('customers', 'customers.id' , '=', 'bookings.customer_id')
->select('bookings.id', 'bookings.start_time', 'bookings.end_time', 'bookings.service', 'staffs.name as Staff-Name', 'customers.name as Customer-Name')
->orderBy('customers.name', 'desc')
->get();
return view('booking.index')
->with('bookings', $bookings);
I had the following problem, simplified example:
$result = Donation::join('user', 'user.id', '=', 'donation.user_id')->where('user.email', 'hello#papabello.com')->first();
$result is a collection of Donation models. BUT CAREFUL:
both tables, have a 'created_at' column. Now which created_at is displayed when doing $result->created_at ? i don't know. It seems that eloquent is doing an implicit select * when doing a join, returning models Donation but with additional attributes. created_at seems random. So what I really wanted, is a return of all Donation models of the user with email hello#papabello.com
solution is this:
$result = Donation::select('donation.*')->join('user', 'user.id', '=', 'donation.user_id')->where('user.email', 'hello#papabello.com')->first();
Yeah, simply rename the column on either table and it should work.
Also what you can do is, rename the user.name column to anything, also rename sender column of conversation_messages to id and perform a natural join.
I have a table with email addresses and want to make a disctinct select (dont have duplicate email addresses in my result). The column with the email address is called 'mail_address'
I have tried:
ContactMail::distinct('mail_address')->get();
And:
ContactMail::distinct()->get();
But both give me just the complete table, also the rows where I have the same email address.
The complete query that I am building looks like this:
$list = ContactMail::where('campaign_id', '=', $campaign_id)
->where('mail_address', '!=', '')
->distinct('mail_address')
->get();
What am I doing wrong? I did not find good docu for distinct.
Using distinct in ORM is a bit pointless - in the end every model is distinct.
So I suggest, that you don't load the models, but single field that you need:
$list = ContactMail::where('campaign_id', '=', $campaign_id)
->where('mail_address', '!=', '')
->distinct()
->lists('email_address');
This way you get an array of distinct emails, instead of full models, or incomplete models when using select and get
$list = ContactMail::where('campaign_id', '=', $campaign_id)
->where('mail_address', '!=', '')
->select('mail_address')
->distinct()
->get();