Laravel Eloquent - Select Certain Columns Combine with Eager Loading - php

How to select certain columns on parents table while querying with eager loading?
$accounts = \App\Account::with('status')->get();
Return
[{"id":1,"username":"kuhn.desiree","email":"quentin.gleason#example.net","last_login":"2009-04-02 23:21:20","created_at":"2017-07-15 19:07:03","updated_at":"2017-07-15 19:07:03","status_id":13,"status":{"id":13,"name":"ab","desc":"Quos quas.","created_at":"2017-07-15 19:07:01","updated_at":"2017-07-15 19:07:01"}}]
I only want username and email on Account table.

Try to use this code:
$accounts = \App\Account::with(['status' => function($q)
{
$q->select('username', 'email');
}])->get();

one way is using select() method
$accounts = \App\Account::with('status')->select('username', 'email','status_id')->get();
If you would like to retrieve a Collection containing the values of a single column, you may use the pluck method.:
accounts = \App\Account::with('status')->pluck('username', 'email');

You want to add a select call:
$accounts = \App\Account::with('status')->select('username', 'email')->get();

Related

Eloquent order relationship results

I have a simple eloquent query and want to include another table with my results, however, the order of relationship results is incorrect.
Is it possible to order the results without using an SQLRAW statement
$groups = AttributeGroup::with('attribute')->where('page_id', $page->id)->get();
What I would like -
$groups = AttributeGroup::with('attribute')->orderBy('iteration', 'DESC')->where('page_id', $page->id)->get();
I get the error of Unknown column because this column is part of relationship table.
This will order each attribute relation of every attribute group result:
$groups = AttributeGroup::with(['attribute' => function ($query) {
$query->orderBy('iteration', 'DESC');
}])->where('page_id', $page->id)->get();
Is this what you want to achieve?
You can use closures to change the query when using with and has.
$groups = AttributeGroup::with(['attribute' => function($query){
$query->orderBy('iteration');
})->where('page_id', $page->id)->get();
Details are available on https://laravel.com/docs/5.6/eloquent-relationships#constraining-eager-loads

retrieve single row in LARAVELusing eloquent

i am using laravel 5.1 and want to retrieve a single row in the database then manipulate it after.
my current code is
$profiles = Profile::where('user_id', $this->user->user_id)
->where('profile_code', $this->user->profile_code)
->get();
foreach($profiles as $profile ){
$data['address'] = $profile->address;
}
why cant i do it like this?
$profiles = Profile::where('user_id', $this->user->user_id)
->where('profile_code', $this->user->profile_code)
->get();
$data['address'] = $profiles->address;
am i using a wrong function or something?
thanks in advance.
Try this:
$data['address'] = $profiles[0]->address;
When you are using get(), it returns an array of Std class object.
In addition to retrieving all of the records for a given table, you may also retrieve single records using first. Instead of returning a collection of models, these methods return a single model instance:
// Retrieve the first model matching the query constraints...
$flight = App\Flight::where('active', 1)->first();
laravel 5.8
Retrieving A Single Row / Column From Profile
If you just need to retrieve a single row from the database table, you may use the first() method. This method will return a single stdClass object:
$Profile = DB::table('Profiles')->where('user_id', $this->user->user_id)
->where('profile_code', $this->user->profile_code)->first();
If you don't even need an entire row, you may extract a single value from a record using the value() method. This method will return the value of the column directly:
$address = DB::table('Profiles')->where('user_id', $this->user->user_id)
->where('profile_code', $this->user->profile_code)->value('address');

(Laravel) only retrieving users that have a relationship

In my site I have users and items. Users can create items. I want to get an array that has all users, where the users which have an item go first and the users which do not have an item go after.
So far I have done this:
$users = User::all();
foreach($users as $user) {
if ($user->item) {
$sortedUsers + $user;
}
// now loop again and add users without relationship
This is pretty inefficient and I'm sure there's a much better way to do it.
You can query on the existence of a relationship
$users = User::has('items')->with('items')->get();
with that syntax you are telling laravel to fetch all users that have a item and to eager load the items;
Edit:
After reading it does not look like you actually want the items just the users that have a item in that case all you need is
$users = User::has('items')->get();
Without seeing the relation of Items to Users I'm not sure if this will work but you can try the following:
$users = Users::select('users.*')->orderBy('items.id')->with('items')->get();
Or it might work with just:
$users = Users::orderBy('items.id')->with('items')->get();
Update
$users = Users::orderBy('items.id')->join('items', 'items.user_id', '=', 'users.id')->get();
you can try
$users = User::with('item')->get();
foreach ($users as $user) {
echo $User->item->name;
}
You can use has() to get users with items and doesntHave() to get users without items:
$withItems = User::has('items')->get();
$withoutItems = User::doesntHave('items')->get();
And then merge() two collections:
$users = $withItems->merge($withoutItems);
You said you want an array, so you can convert result into an array with toArray()
$array = $users->toArray();

Laravel: find if a pivot table record exists

I have two models which are joined by a pivot table, User and Task.
I have a user_id and a task_id.
What is the neatest way to check whether a record exists for this combination of user and task?
You have a couple options depending on your situation.
If you already have a User instance and you want to see if it has a task with a certain id, you can do:
$user = User::find(1);
$hasTask = $user->tasks()->where('id', $taskId)->exists();
You can reverse this if you have the Task instance and want to check for a user:
$task = Task::find(1);
$hasUser = $task->users()->where('id', $userId)->exists();
If you just have the ids, without an instance of each, you could do the following:
$hasPivot = User::where('id', $userId)->whereHas('tasks', function ($q) use ($taskId) {
$q->where('id', $taskId);
})
->exists();
You can also try this, this is working in Laravel 5.7
$user = User::find(1);
$hasTask = $user->tasks->contains($taskId);
But the better way will be
$hasTask = $user->tasks()->where('tasks.id', $taskId)->exists();
may be you search this?
$users = User::has('task')->get();
Easiest to read for me is:
$user->tasks()->exists();
You can use the code below:
$user = User::find(1);
$hasTask = $user->tasks()->where('task_id', $taskId)->exists();

How to select certain colums in yii CActive record?

I want to get all rows , certain columns using CActive record
I heard about findAll(); but it returns all rows, colums
$models = Users::model()->findAll();
How to get certain columns for example, only username, password for all users?
You can do with CDbCriteria
$criteria = new CDbCriteria;
$criteria->select = 't.username, t.password '; // select fields which you want in output
$models = Users::model()->findAll($criteria);
If you want the result in the form of array try this
$records= Yii::app()->db->createCommand()
->select('username,password')
->from('users')
->queryAll();
If as an object then kumar_v has already given an answer
the Kumar_v 's answer is completely correct, but if you want only username and password (or any two fields),
you can also use CHtml::listData() function like this :
$users=CHtml::listData(Users::model()->findAll(array('condition'=>'*condition*',
'limit'='*limit*')),"username", "password");
the $users is an array like this :
$users = array(
'username1'=>'password1',
'username2'=>'password2',
.
.
.
);
and of course you can access to a username's password simply by $users['username1']
You could use as usual sql query but getting so would not be in yii standard
So get findAll() and get the data that you want. that is proposed and best.

Categories