This question already has answers here:
Laravel: How to get last N entries from DB
(13 answers)
Closed 1 year ago.
How can i make a query to return me the most recent added objects
Controller :
public function __construct()
{
$this->middleware(['auth', 'verified']);
}
public function index(Request $request){
$object = Obj::with('children.objectable', 'ancestorsAndSelf.objectable')->ForTheCurrentTeam()->where(
'uuid', $request->get('uuid', Obj::ForTheCurrentTeam()->whereNull('parent_id')->first()->uuid)
)
->firstOrFail();
return view('home', [
'object' => $object,
'ancestors' => $object->ancestorsAndSelf()->breadthFirst()->get(),
'recent' => $object->orderBy('created_at','desc')->get(),
dd($object),
]);
I am trying to make something like this but for the most recent added objects. How would i do it?
Use latest():
$object = Obj::with('children.objectable', 'ancestorsAndSelf.objectable')->ForTheCurrentTeam()->where(
'uuid', $request->get('uuid', Obj::ForTheCurrentTeam()->whereNull('parent_id')->first()->uuid)
)
->latest()
->firstOrFail();
you can use order by desc and take a specified number of records
'recent' => $object->orderBy('created_at','desc')->take(5)->get()
this will take the 5 latest
Related
I am calling an array of all the comments of a poll by using the following code:
$poll = Poll::find($id);
return view('pages.poll', ['poll' => $poll, 'comments' => $poll->comments]);
and the links between Comments and Polls are the following:
Comment.php
public function poll() {
return $this->belongsTo(Poll::class, 'poll_id');
}
Poll.php
public function comments() {
return $this->hasMany(Comment::class, 'poll_id');
}
Finally, I would like to sort the array comments coming from $poll->comment by the column likes in the Comment table, something like DB::table('comment')->orderBy('likes')->get();.
Is there any way to do that?
$poll->comments->sortBy('likes')
There's a number of ways you can do this.
Add orderBy('likes') directly to your comments relationship:
Poll.php:
public function comments() {
return $this->hasMany(Comment::class, 'poll_id')->orderBy('likes');
}
Now, any time you access $poll->comments, they will be automatically sorted by the likes column. This is useful if you always want comments in this order (and it can still be overridden using the approaches below)
"Eager Load" comments with the correct order:
In your Controller:
$poll = Poll::with(['comments' => function ($query) {
return $query->orderBy('likes');
})->find($id);
return view('pages.poll', [
'poll' => $poll,
'comments' => $poll->comments
]);
with(['comments' => function ($query) { ... }]) adjusts the subquery used to load comments and applies the ordering for this instance only. Note: Eager Loading for a single record generally isn't necessary, but can be useful as you don't need to define an extra variable, don't need to use load, etc.
Manually Load comments with the correct order:
In your Controller:
$poll = Poll::find($id);
$comments = $poll->comments()->orderBy('likes')->get();
return view('pages.poll', [
'poll' => $poll,
'comments' => $comments
]);
Similar to eager loading, but assigned to its own variable.
Use sortBy('likes'):
In your Controller:
$poll = Poll::find($id);
return view('pages.poll', [
'poll' => $poll,
'comments' => $poll->comments->sortBy('likes')
]);
Similar to the above approaches, but uses PHP's sorting instead of database-level sorting, which can be significantly less efficient depending on the number of rows.
https://laravel.com/docs/9.x/eloquent-relationships#eager-loading
https://laravel.com/docs/9.x/eloquent-relationships#constraining-eager-loads
https://laravel.com/docs/9.x/collections#method-sortby
https://laravel.com/docs/9.x/collections#method-sortbydesc
This question already has answers here:
Laravel Eloquent Pluck without losing the key
(7 answers)
Closed 1 year ago.
I would like Laravel query-builder to return an array of key => value.
For example, for users table which has columns username, email return something like:
Array
(
[email1] => username1
[email2] => username2
)
Now, I can achieve each one of the with either pluck('username') or with keyBy('email').
I can use php array functions to manipulate result returned by keyBy in order to achieve what I want:
$tmpRes = DB::table('users')
->select(['username', 'email'])
->get()->keyBy('email')->toArray();
$res = array_map(function ($el) {
return $el->username;
}, $tmpRes);
I wonder whether there is a direct way to do so.
Pluck actually allows a second parameter as a key
public static function pluck($column, $key = null)
So all you have to do is pass that in
$tmpRes = DB::table('users')
->pluck('username', 'email')
->toArray();
This question already has answers here:
Get Specific Columns Using “With()” Function in Laravel Eloquent
(19 answers)
Closed 2 years ago.
So I have a query that I only want to get specific columns in a relation but is not working. I'm using Laravel 5.2 by the way. Here's what I have:
$job = Job::query()->whereId($job_id)
->with([
'jobType' => function (Relation $query) {
$query->select(['name']);
},
])
->first();
If I do that, the jobType relationship returns null as seen below:
And if I'll remove the $query->select(['name']);, it has the data from job_type table. How can I just successfully get specific column from a table?
Maybe This can.. To get the specific column you need a specific jobtype
$job = Job::query()->whereId($job_id)
->with(['jobType' => function ($q) use($jobType) {
$q->where(// check the condition on jobtype table);
$q->select(['name']);
},
])
->first();
I have a query that returns a boolean field (by the way, I'm on an SQL Server) on my REST API developed with Laravel and a few days ago it was returning the value as true/false, but now it returns that boolean value as String: "1"/"0".
Any idea on what could it be?
I tried using casting on my Model like this:
protected $casts = [
'status' => 'boolean',
];
This is my query:
return DB::table('dbo.visits as V')
->leftJoin('dbo.reports AS R', 'R.id_visit', '=', 'V.id')
->select('R.id','R.status'); // status is the boolean
Thanks in advance.
When you're defining the following:
protected $casts = [
'status' => 'boolean',
];
You're defining it on the model. However, when you initiate your query using DB::table(), you're not using the model, so the binding doesn't actually apply. Initiate your query using your model:
return Visit::leftJoin('dbo.reports AS R', 'R.id_visit', '=', 'dbo.visits.id')
->select('R.id','R.status'); // status is the boolean
Note: Had to adjust query to dbo.visits.id from V.id due to aliasing not being available at that point.
Defining casts is working when you are using Eloquent models. In code you provided you use query builder and then Eloquent models are not used at all, so no casts are done.
You could use Eloquent: API Resources
/*Controller*/
$sel_visit= Visit::leftJoin('dbo.reports AS R', 'R.id_visit', '=', 'dbo.visits.id')->select('R.id','R.status')->get(); // status is the boolean
VisitResource::collection($sel_visit);
Then using a API Resources
public function toArray($request)
{
if($this->status==1) { $status=true;} else {$status=false;}
return [
'id' => $this->id,
'status' => $status
];
}
What you would like to do is add this function to your model. Every time you use your model to retrieve data, this function matching the attribute name will be called to convert your raw data from the database to your desired format.
public function getStatusAttribute($value)
{
return $value ? 'Yes' : 'No';
}
This question already has answers here:
PHP variables in anonymous functions
(2 answers)
Closed 7 years ago.
I am trying to query for users that are assigned to a certain project in CakePHP. How could I basically achieve this:
$projectId = //Project ID query result.
$users = $this->Tickets->Users
->find('list', ['limit' => 200])
->innerJoinWith(
'ProjectsUsers', function($q){
return $q->where(['ProjectsUsers.project_id' => $projectId]);
}
);
This code works when not using variables (eg. replacing $projectId with 8) but when I try to use variables I get: Undefined variable: projectId
How can I pass variables into innerJoinWith?
If you mean how to inherit a variable from the parent scope, you'd do it like this.
$users = $this->Tickets->Users
->find('list', ['limit' => 200])
->innerJoinWith(
'ProjectsUsers', function($q) use($variableToPass) {
return $q->where(['ProjectsUsers.project_id' => $variableToPass]);
}
);