Consider me as laravel beginner
The goal is: I have two colums, now I need the id to be prefixed with the component name of same row in the table.
For Example (Working)... I have Mysql like
SELECT CONCAT(components.name," ", components.id) AS ID
FROM `components`
And output is
ID
|TestComp 40 |
-------------
|component 41 |
-------------
|test 42 |
I need the same in laravel eloquent way, as here Component is Model name. So i tried something like
$comp=Component::select("CONCAT('name','id') AS ID")->get()
but it doesn't work.
I think because the syntax is wrong.
Kindly help me with the correct syntax. Using laravel Models.
Note: I made the above query, referring this as which available on internet.
User::select(DB::raw('CONCAT(last_name, first_name) AS full_name'))
You need to wrap your query in DB::raw:
$comp = Component::select(DB::raw("CONCAT('name','id') AS ID"))->get()
Also, note because you are doing your query like this, your model might behave differently, because this select removes all other fields from the select statement.
So you can't read the other fields from your model without a new query. So ONLY use this for READING data and not MODIFYING data.
Also, to make it in a nice list, I suggest you modify your query to:
$comp = Component::select(DB::raw("CONCAT('name','id') AS display_name"),'id')->get()->pluck('display_name','id');
// dump output to see how it looks.
dd($comp);// array key should be the arrray index, the value the concatted value.
I came to this post for answers myself. The only problem for me is that the answer didn't really work for my situation. I have numerous table relationships setup and I needed one of the child objects to have a concatenated field. The DB::raw solution was too messy for me. I kept searching and found the answer I needed and feel it's an easier solution.
Instead of DB::raw, I would suggest trying an Eloquent Accessor. Accessors allow you to retrieve model attributes AND to create new ones that are not created by the original model.
For instance, let's say I have a basic USER_PROFILE table. It contains id, first_name, last_name. I have the need to CONCAT the two name attributes to return their user's full name. In the USER_PROFILE Model I created php artisan make:model UserProfile, I would place the following:
class UserProfile extends Model
{
/**
* Get the user's full concatenated name.
* -- Must postfix the word 'Attribute' to the function name
*
* #return string
*/
public function getFullnameAttribute()
{
return "{$this->first_name} {$this->last_name}";
}
}
From here, when I make any eloquent calls, I now have access to that additional attribute accessor.
| id | first_name | last_name |
-------------------------------
| 1 | John | Doe |
$user = App\UserProfile::first();
$user->first_name; /** John **/
$user->fullname; /** John Doe **/
I will say that I did run into one issue though. That was trying to create a modified attribute with the same name, like in your example (id, ID). I can modify the id value itself, but because I declared the same name, it appears to only allow access to that field value and no other field.
Others have said they can do it, but I was unable to solve this questions EXACT problem.
I working on posgresql and mysql:
DB::raw('CONCAT(member.last_name, \' \', member.first_name) as full_name')
$text = "other";
$limit = 100
public function get_data($text, $limit)
{
$result = $this->select('titulo', 'codigo', DB::Raw("CONCAT(codigo, ' ', titulo_long) AS text_search"))
->where('tipo', '=', 2)
->having('text_search', 'LIKE', "%$text%")
->limit($limit)
->get();
return $result;
}
}
Here is the example of columns concatenation in Laravel.
I need to search the user by name and I have three columns for the user name (name_first, name_middle, name_last), so I have created a scope in Laravel UserModel which takes $query and user name as the second parameter.
public function scopeFindUserByName($query,$name) {
// Concat the name columns and then apply search query on full name
$query->where(DB::raw(
// REPLACE will remove the double white space with single (As defined)
"REPLACE(
/* CONCAT will concat the columns with defined separator */
CONCAT(
/* COALESCE operator will handle NUll values as defined value. */
COALESCE(name_first,''),' ',
COALESCE(name_middle,''),' ',
COALESCE(name_last,'')
),
' ',' ')"
),
'like', '%' . $name . '%');
}
and you can use this scope anywhere you need to search user by his name, like
UserModel::findUserByName("Max Begueny");
OR
$query = UserModel::query();
$query->findUserByName("Max Begueny");
To check the result of this SQL query just go through from this post.
https://stackoverflow.com/a/62296860/11834856
this code should work:
User::select(\DB::raw('CONCAT(last_name, first_name) AS full_name)')
Scrubbing the Data: Before using Laravel and now, when developing in other languages, I would use CONCAT() on a regular basis. The answers here work to a degree but there still isn't an elegant way to use CONCAT() in Laravel/Eloquent/Query Builder
that I have found.
However, I have found that concatenating the cols AFTER returning the results works well for me and is usually very fast - Scrubbing the data - ( unless you have a huge result which should probably be "chunked" anyway for performance purposes ).
foreach($resultsArray AS $row){
$row['fullname'] = trim($row['firstname']).' '.trim($row['lastname']);
}
This is a tradeoff of course but, personally, I find it to be much more manageable and doesn't limit my use of Eloquent as intended as well as the Query Builder. ( the above is pseudo code - not tested so tweak as needed )
There are other workarounds as well that don't mess with Eloquent/Query Builder functionality such as creating a concatenated col in the table, in this case full_name - save the full name when the record is inserted/updated. This is not uncommon.
Related
i need to get specific columns in the 2 methods that is being chained inside 'with', but it doesnt work, how can i select specific columns in each method inside of the 'with' method.
Event::with('eventBookmakers.bookmakerInfo')->find(2);
It's possible like this:
Event::with('eventBookmakers:column', 'eventBookmakers.bookmakerInfo:column')->find(2);
Remember to select the foreign key columns (e.g. event_id).
Try this, change column name to what column you want to retrieve.
Event::with('eventBookmakers.bookmakerInfo:columnName')->where('id', 2)->get();
or
Event::with('eventBookmakers.bookmakerInfo:columnName')->find(2);
Since you're selecting the two interrelated tables (relations) using dot . You may use select() and with() in a closure to add constraint and add the relations as well. So you'll end up with something like:
Event::with(['eventBookmakers' => function($bookmakers){
$bookmakers->select('id', 'event_id')->with(['bookmakerInfo' => function($info) {
$info->select('id', 'bookmaker_id');
}]);
}])->find(2);
Note the event_id passed to the first select ensure the relationship is loaded between Event and EventBookmaker(you can replace it with the relation_id you use instead) and same thing with using bookmaker_id so that it may load relation between Bookmaker and BookmakerInfo
I am trying to select the users who are listed in the given range of their first name initials.
For example, if the name of the person starts with letter C then the user will select the range, lets say, A-E. So for that, he will click on range A-E and that range will display all the users whose name starts with either A, B, C, D and E.
In order to do that I am trying to query the laravel eloquent, but I cannot find the desired solution. On bit of research, I found this link that provides the solution, but it didn't provided me what I am looking for.
The query that I did is:
public function getAllUsers(Request $request)
{
$users = User::where('account_type', 'beneficiary')->latest()->get();
if($request->range !== null) {
$users = User::where('account_type', 'beneficiary')->where('full_name', "REGEXP '^".$request->range.".*$'")->latest()->get();
dd($users); // returned an empty Collection object
}
return view('pages.beneficiaries', compact('users'));
}
Bottom Line: Fetch the users whose name starts within the given range that the user will select.
Any help is highly appreciated. Thanks.
P.S: I know this might be quite simple to solve, but I am failing in it.
UPDATE 1: Solution
With the help of #Armen, I was able to solve the issue. The query that I passed to the eloquent model is the following:
// Notice the curly braces and also the removal of single quotes
$users = User::where('account_type', 'beneficiary')
->where('full_name', 'REGEXP', "^[{$request->range}].*$")
->get();
According to your found example (mentioned in issue description) value of REGEXP should be in scopes [] like this '^[A-E].*$' so change your second where to where('full_name', "REGEXP '^[".$request->range."].*$'") and also take into account Upper and Lowercase lettera-e is not same as A-E
UPDATE
as we founded out with #user3514160 the where condition should look like this
->where('full_name', 'REGEXP', "^[{$request->range}].*$")
I am using Cassandra last few days. I am using PHPCassa library for that.
When I am trying to use the following code, Its not working correctly.
require_once('phpcassa/connection.php');
require_once "phpcassa/columnfamily.php";
// Create new ConnectionPool like you normally would
$pool = new ConnectionPool("newtest");
// Retrieve a raw connection from the ConnectionPool
$raw = $pool->get();
$rows = $raw->client->execute_cql_query("SELECT * FROM User WHERE KEY='phpqa'", cassandra_Compression::NONE);
echo "<pre>";
print_r($rows);
echo "<pre>";
// Return the connection to the pool so it may be used by other callers. Otherwise,
// the connection will be unavailable for use.
$pool->return_connection($raw);
unset($raw);
Its returning nothing, I have also tried following queries
$rows = $raw->client->execute_cql_query("SELECT * FROM User WHERE age='32'", cassandra_Compression::NONE);
$rows = $raw->client->execute_cql_query("SELECT * FROM User WHERE name='jack'", cassandra_Compression::NONE);
But When I tried
$rows = $raw->client->execute_cql_query("SELECT * FROM User", cassandra_Compression::NONE);
Its given the correct answer, displayed all the rows. Please advise me, how to use 'WHERE' properly.
Keyspace Details
Strategy Class: org.apache.cassandra.locator.SimpleStrategy
Strategy Options: None
Replication Factor: 1
Ring
Start Token: 6064078270600954295
End Token: 6064078270600954295
Endpoints: 127.0.0.1
In cassandra you cant just query a 'table' as you would normally. You need to set up secondary indexes for every column you might want to query.
Say we have a table:
key | User | Age
----------+----------------
phpqa | Jack | 20
You can query directly on the key:
SELECT * FROM User WHERE key='phpqa';
But to carry out other WHERE queries you'd need a secondary index on the columns you want to have available in the WHERE clause.
What can you do to make your querying flexible in the way that you desire:
Secondary indexes as described above.
Use composite columns as your key. Its a good idea if you only have 2-3 columns you want to query, but have a read through this article detailing how and when to use composite keys, and here is a link in how to implement it in phpcassa.
Add 'name' and 'age' as secondary indexes:
CREATE INDEX name_key on User( name );
CREATE INDEX age_key on User( age );
Then you should be able to use your select statement(s).
Read more here.
you are using a reserved word as a column name:
http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
$raw->client->execute_cql_query("SELECT * FROM User WHERE KEY='phpqa'",
cassandra_Compression::NONE)
I heed two variables storing the maximum id from a table, and the minimum id from the same table.
the first id is easy to be taken ,using find() and a query like
$first = Model::factory('product')->sale($sale_id)->find();
but how can i retrieve the last id? is there a sorting option in the Kohana 3 ORM?
thanks!
Yes, you can sort resulting rows in ORM with order_by($column, $order). For example, ->order_by('id', 'ASC').
Use QBuilder to get a specific values:
public function get_minmax()
{
return DB::select(array('MAX("id")', 'max_id'),array('MIN("id")', 'min_id'))
->from($this->_table_name)
->execute($this->_db);
}
The problem could actually be that you are setting order_by after find_all. You should put it before. People do tend to put it last.
This way it works.
$smthn = ORM::factory('smthn')
->where('something', '=', something)
->order_by('id', 'desc')
->find_all();
Doing like this, I suppose you'll be :
selecting all lines of your table that correspond to your condition
fetching all those lines from MySQL to PHP
to, finally, only work with one of those lines
Ideally, you should be doing an SQL query that uses the MAX() or the MIN() function -- a bit like this :
select max(your_column) as max_value
from your_table
where ...
Not sure how to do that with Kohana, but this topic on its forum looks interesting.
Suppose that I have a database query which looks like below -
select name, gender, birthday from person where person_id = 1;
When this query is executed, some records from the database is returned. I want to execute this query inside a function, then make a custom object which will contain the exact attributes as the column names, with the corresponding values. As an example, suppose that the object is X. So it will have three attributes which are X->name, X->gender and X->birthday, with the corresponding values from the records.
As a second example, consider the following query -
select test1, test2, test3 from test where test_id = 1;
I want to execute this query inside the same function and using the same method, then generate a custom-object Y which will contain the attributes Y->test1, Y->test2 and Y->test3.
Is it doable in PHP? If so, then how?
Edit: By custom object, I meant any kind of object. It does not need to be an instance of a specific class or something like that. I just want to return an object from that function so that I can populate the appropriate classes from the returned object's property values.
foreach ($result as $key => $value)
{
$your_object->{$key} = $value;
}
EDIT: this answer assumed Archangel used MySQL, which it turns out is not the case. Sorry for the mistake! I'll leave my answer here in case any MySQL folks come across it, as well as to preserve the comments if necessary.
If you don't care about custom classes and only want your custom attribute names in the row objects, this is all you need:
$row_object = mysql_fetch_object($result);
Otherwise, you'll need to write your own class yourself (I'm not sure whether a constructor is needed or the function populates your object with data automatically):
class X
{
public $name;
public $gender;
public $birthday;
}
Then call the function like this:
$row_object = mysql_fetch_object($result, 'X');
There's no built-in way that I know of to generate classes on-the-fly for you; you'll have to write your own classes.