orderBy on whereHas query in Laravel 4.2 - php

how can I sort the return data from a query using whereHas? In my query i have to get the users data which id exist on interest table but i need to sort it using the datetime column from interest. But, the return query do not sort the data at all.
Here's my code snippets in case it would help you understand my problem.
Model (name: User)
//***relationship***//
public function interest(){
return $this->belongsTo('Interest','id','interest_by');
}
Controller
$userInterested = User::whereHas('interest',function($q) use ($id) {
return $q->where('interest_on', $id)
->orderBy('datetime');
});
$userQuery = $userInterested->get();
return $userQuery;

remove return from where has and try this.like
$userInterested = User::whereHas('interest',function($q) use ($id) {
$q->where('interest_on', $id)
->orderBy('datetime');
})->get();
return $userInterested;

$userInterested = User::whereHas('interest',function($q) use ($id) {
return $q->where('interest_on', $id);
})->orderBy('datetime');
$userQuery = $userInterested->get();
return $userQuery;

Related

LARAVEL: How to fetch id dynamically in a query builder?

I want to join multiple tables in laravel with query builder. My problem is that my code only works if I specify the id myself that I want like this:
$datauser = DB::table('users')
->join('activitates','users.id','=','activitates.user_id')
->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
->join('clients','users.id','=','clients.user_id')
->where('users.id','=','1')
->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
->get();
return response()->json($datauser);
But I would want something like this(which I just can't seem to figure out)
public function showuser($id)
{
$userid = User::findOrFail($id);
$datauser = DB::table('users')
->join('activitates','users.id','=','activitates.user_id')
->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
->join('clients','users.id','=','clients.user_id')
->where('users.id','=',$userid)
->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
->get();
return response()->json($datauser);
}
Am I making a syntax mistake? When I check the page for my json response in second page it just returns empty brackets, but when I specify the id it fetches me the right data
The findOrFail method will return the entire user model, with all its properties, since you already have the user id. You dont need to get the entire user model for that, you could just use the $id you receveid as a parameter like this:
$datauser = DB::table('users')
->join('activitates','users.id','=','activitates.user_id')
->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
->join('clients','users.id','=','clients.user_id')
->where('users.id','=',$id)
->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
->get();
return response()->json($datauser);
public function showuser($id)
{
$getUserByID = User::findOrFail($id); //not used
$userData = DB::table('users')
->join('activitates','users.id','=','activitates.user_id')
->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
->join('clients','users.id','=','clients.user_id')
->where('users.id','=',$id)
->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
->get();
return response()->json($userData);
}
But the best way is to have relations set on models
public function showuser($id)
{
$userData = User::where('id', $id)->with(['activitates','taga_cars','clients'])->first();
return response()->json($userData);
}

get last id form database in laravel-8

I want to get only the last inserted data from my database.
Here, I get all data from the database but I want only the last value.
This is ProductController.php
function indextwo()
{
return DB::select("select * from products");
}
This is web.php
Route::get('products_link', [ProductController::class, 'indextwo']);
Here is my current output:
You can get the last id using Query Builder and Eloquent.
Query Builder
function indextwo() {
return DB::table('products')->orderBy('id', 'DESC')->first();
}
Eloquent
function indextwo() {
return Product::orderBy('id', 'DESC')->first();
}
Maybe you can use latest() function for get
$user = DB::select("select * from products")
->latest()
->first();
Maybe you can use Model name direct in controller like your model name is "Product" and also use limit() and latest()
$user = Products::latest()->limit(1);
A very simple way you can follow
Product::query()->latest()->first()
It will return you the latest inserted data according to order by id desc.
Another way :
Product::query()->orderByDesc('id')->first();

How to get data from relation in Laravel used in with()?

I am getting data from multiple tables in relation with each other. But in one of the relation I want to get userAnswers records by where('user_id, $userID). What is correct syntax for it
public function survey_completed_show($userSurvey, $userID)
{
$userSurvey = UserSurvey::with('survey.questions.userAnswers')->find($userSurvey);
return view('surveys.conducted-answers', compact('userSurvey'));
}
I just want to get answers of the selected User, I am currently getting all answers by each user
you can use deep with:
$userSurvey = UserSurvey::with(['survey'=>function($query)use( $userID){
$query->with(['questions'=>function($query)use( $userID){
$query->with(['userAnswers'=>function($query)use( $userID){
$query->where('user_id', $userID);
}]);
}]);
}])->find($userSurvey);
Assuming you only need to filter the relation and not the UserSurvey you might wanna try this
public function survey_completed_show($userSurvey, $userID)
{
$userSurvey = UserSurvey::with(['survey.questions.userAnswers' => function($q) use ($userID){
$q->where('user_id', $userID);
}])->find($userSurvey);
return view('surveys.conducted-answers', compact('userSurvey'));
}

Order data by pivot table when try to use With

I have tables Polfzms <- Genes
Polfzm model have next relation
public function gene()
{
return $this->belongsTo('App\Gene');
}
I need get all data from Polfzms table with data from Genes table and order it by name from pivot table (Genes). I try next
$data = Polfzm::with([
'gene' => function ($query) {
$query->orderBy('name', 'asc');
},
])->get();
but it not order data by name. How can I do it?
You could try to set this in the relationship definition:
Polfzm.php
public function gene()
{
return $this->belongsTo('App\Gene')->orderBy('name', 'asc');
}
Then in your controller:
$data = Polfzm::with('gene')->get();
If I understand correctly, you could use a collection sortBy helper for this one.
An example could be:
$data = Polfzm::with('gene')
->get()
->sortBy(function ($polfzm) {
return $polfzm->gene->name;
});

Yii2 viaTable multiple variables

I'm trying to find a number of UserComment using a viaTable on the table called user_comment_user in Yii2. However I can't seem to get my variables/query inserted properly.
Currently I've got two queries set up, to check if (on their own) they achieve the correct result, which they do.
These are the two queries that somehow have to be merged into one:
public function findConversation($id)
{
$query = $this->hasMany(UserComment::classname(), ['id'=>'user_comment_id'])
->viaTable('user_comment_user', ['sender_id'=>'id'], function ($query) use ($id) {
$query->andWhere(['receiver_id'=>$id]);
});
$query2 = $this->hasMany(UserComment::classname(), ['id'=>'user_comment_id'])
->viaTable('user_comment_user', ['receiver_id'=>'id'], function ($query) use ($id) {
$query->andWhere(['sender_id'=>$id]);
});
return $query;
}
The answer was actually much simpler than I had imagined:
public function findConversation($id)
{
$query = UserComment::find();
$query->leftJoin('user_comment_user', 'user_comment_user.user_comment_id=user_comment.id');
$query->where(['receiver_id'=>$this->id, 'sender_id'=>$id]);
$query->orWhere(['receiver_id'=>$id, 'sender_id'=>$this->id]);
$query->orderBy(['created_at'=>SORT_DESC]);
return $query;
}

Categories