Multiple aliases of a single table column with Eloquent ORM - php

Is it possible to have multiple Aliases from a single table column. If I do the following in MySQL I get the result I want:
SELECT name, name AS label, name AS value FROM `tags` WHERE 1
But, if I try to do:
$query->select('name, name AS label, name AS value');
..it tells me SQLSTATE[42S22]: Column not found: 1054 Unknown column 'name,' in 'field list' (SQL: selectname,asASfromtagswheretags.deleted_atis null group bynameorder bynameasc)
If I try to do
$query->select('name AS name, name AS label, name AS value');
..it doesn't throw an error, but instead only gives me one alias (name). How can I achieve this using Eloquent ORM? Thanks

When you try select laravel do this:
public function select($columns = array('*'))
{
$this->columns = is_array($columns) ? $columns : func_get_args();
return $this;
}
And when you pass the string, laravel thinks you passed few args, so you can do:
$query->select(['name AS name', 'name AS label', 'name AS value']);
Or
$query->selectRaw('name AS name, name AS label, name AS value'):
Or
$query->select(DB::raw('name AS name, name AS label, name AS value'));
Or like said #Jarek Tkaczyk
$query->select('name as name', 'name as label', 'name as value');

Try this:
$query->select(DB::raw('name AS name, name AS label, name AS value'));
Link of Laravel Doc

Related

How to change id to uuid?

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select count(*) as aggregate from shops where username = csesumonpro and id 5d4cb970-197d-41db-90e1-26988d543935)
how to change id to uuid when execute query? i am using uuid in my model replace of id i already defined
protected $primaryKey = 'uuid'; // in my model
Show above error when use unique email validation, unique email validation execute a query query autonomic capture id but i need uuid .otherwise everything is ok.
'email' => 'unique:users,email,'.$user->id // validation code
You need to specify the uuid column name as you are not using numerical IDs.
So it should read:
'email' => 'unique:users,email,'.$user->uuid.',uuid'

Change the name of the column to be taken from the database

How can I change the questioned to the database which is automatically generated.I have in blade template this
{{\Illuminate\Support\Facades\Auth::user()->friends()->get()}}
and it generates
Unknown column 'friends.user_id' in 'where clause' (SQL: select * from `friends` where `friends`.`user_id` = 1 and `friends`.`user_id` is not null
because my column name is user_id1 insted user_id.
and I do not know why the query to the database takes the user_id value instead of user_id1. How can I change it ?
Define the custom foreign key in the friends relationship:
public function friends()
{
return $this->hasMany(Friend::class, 'user_id1');
}

How to return appended field when want to select specific column in laravel

I added a full_name field to User model like this:
protected $appends = ['full_name'];
public function getFullNameAttribute()
{
return $this->name . ' ' . $this->family;
}
On the other hand I want to select and return specific columns along with full_name field like this:
return User::all('user_id', 'username', 'full_name')
But laravel gets this error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'full_name' in 'field list' (SQL: select user_id, username, name, family, full_name from users where users.deleted_at is null)
How can I do what I want?
I think you don't need to specify that in your select column.. it's already attached with your result set.
If you want specific columns, than you need to probably user $hidden attributes and make them visible whenever you want.
You can't use append attribute in query.
the full_name only can be access after query.. bcoz full_name is not attach with the result
$users = User::all();
return $users[0]->full_name; //this requred getFullNameAttribute like above
If you still want to do with query. Do in DB query instead.. this no need to $append attribute. full_name already attach with the result
return User::select('user_id', 'username' , DB::raw('CONCAT(name, " ", family) AS full_name'))->get();
Hello you can get two or more column value concated using query like this,
return $user = User::select('user_id', 'username',DB::raw("CONCAT('first_name', " ",'last_name') AS full_name" 'full_name');
Or if you want to concat column from retrieved array you can do like this,
$user = User::all();
foreach($user as $single){
$user->full_name = $single->first_name ." ".$single->last_name
}
print_r($user);
happy coding.

Laravel 5.3 update request with unique rule with exception

I have request for updating page. When adding new page request is like:
'title'=>'required|max:70|unique:pages',
but when I'm updating page title must be unique but need to check all other titles except one already entered.
I searched Google for all possible solutions but nothing works.
I tried:
'title'=>"required|max:70|unique:pages, title,{$this->id}",
'title'=>'required|max:70|unique:pages, title,'.$this->id,
'title'=>'required|max:70|unique:pages, title,'.$this->input('id'),
rule is inside rules method
public function rules()
{
return [
'title'=>'required|max:70|unique:pages, title,'.$this->id,
...
]
I'm getting this error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column ' title' in 'where clause' (SQL: select count(*) as aggregate from `pages` where ` title` = test and `id` <> )
In my mysql I have id (lowercase) column that is primary key and title column (also lowercase).
You have a bug here:
public function rules()
{ This space is causing trouble
|
return [
'title'=>'required|max:70|unique:pages, title,'.$this->id,
...
]
Should be
public function rules()
{ Space removed
|
return [
'title'=>'required|max:70|unique:pages,title,'.$this->id,
...
]
SQLSTATE[42S22]: Column not found: 1054 Unknown column ' title'
It seems that it's searching for a column named " title", it may be stupid but double check that the column name is sent without a space at the beggining.

Laravel - Access relationship through other

I have the following tables:
entries
- id
- category_id
- name
field
- id
- category_id
- name
field_values
- id
- entry_id
- field_id
- value
category
- id
- name
Each Category has certain fields. If I add an entry, I choose the category and I can enter the values for the field for the entry.
Let's say we have the Category "Venues". Venues has the custom field named "Capacity". If I add a news entry, I need to fill the field "Capacity".
This is how I read the fields and their values for an entry:
#foreach($data->field_values as $values)
{{$values->field->name}}: {{$values->value}}
#endforeach
I can only access the field table through the "field_values" table. Isn't it possible to access field directly from entry maybe with an hasManyThrough ?
This (in Entry Model):
public function fields()
{
return $this->hasManyThrough('App\Field', 'App\FieldValues');
}
throws the following mysql error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'fields.field_values_id' in 'on clause' (SQL: select `fields`.*, `field_values`.`entry_id` from `fields` inner join `field_values` on `field_values`.`id` = `fields`.`field_values_id` where `field_values`.`entry_id` in (3))
Why I need to add a field_values_id to Field? Isn't there a different approach?
I just want to foreach through entry->field and not do it by entry_field_values->field
If you just want to access the Fields for an entry, why not do a hasMany relationship ?
Entry Model:
public function fields()
{
return $this->hasMany('App\Field');
}
Then you can get all the fields for an entry as:
$fields = $entry->fields()->get();

Categories