orderby with eager loading, laravel - eloquent

I have a table called chat which is joined with users and messages (messages are joined with users), the query works fine just I am trying to add orderby with created_at (desc) but it has to be from the table messages. help me out here. Thanks in advance. Below is my query,
return new GroupDirectChat(
Chat::with(['messages.users', 'users' => function ($query) {
$query->where('id', '!=', Auth::id());
}])
->where('direct_chat', 1)
->whereHas('users', function ($query) {
$query->where('id', '=', Auth::id());
})
->get()
);

Combine a JOIN with a subquery:
$chats = Chat::select('chats.*')
->join('messages', 'messages.chat_id', 'chats.id')
->where('chats.direct_chat', 1)
->where('messages.id', function ($query) {
$query->select('id')
->from('messages')
->whereColumn('chat_id', 'chats.id')
->latest()
->limit(1);
})
->whereHas('users', function ($query) {
$query->where('id', '=', Auth::id());
})
->latest('messages.created_at')
->with(['messages.users', 'users' => function ($query) {
$query->where('id', '!=', Auth::id());
}])
->get();
Note that this query only selects chats with at least one message.

Related

Eloquent query not working Laravel 5.4

I have the following query and it is not working as expected.
$students = StudentStatus::with(['user.studentProgramme' => function ($query) {
$query->where('department_course_id', request('studyCourse'));
}], 'level', 'user.studentProgramme.course')
->where('level_id', request('level'))
->where('status', 0)
->get();
The inner WHERE, that is $query->where('department_course_id', request('studyCourse')) is ignored and I don't know why.
Is there something I am missing out?
This may be a scope issue try:
$studyCourse = ;
$students = StudentStatus::with(['user' => function($query) {
$query->with(['studentProgramme' => function ($query) {
$query->where('department_course_id', request('studyCourse'));
}]}], 'level', 'user.studentProgramme.course')
->where('level_id', request('level'))
->where('status', 0)
->get();

Laravel: How can I join a related table to use orderBy correctly?

Here is the query I am using to get results of a camp:
$camp = Camp::where('camps.id', $camp_id)
->with(['athletes' => function ($q) use ($camp_id) {
$q->with(['kickoffs' => function ($q) use ($camp_id) {
$q->where('camp_id', $camp_id);
$q->orderBy('id', 'desc');
}]);
$q->with(['kickoff_results' => function ($q) use ($camp_id) {
$q->where('camp_id', $camp_id);
$q->orderBy('score', 'desc');
}]);
But the results are not getting ordered correctly. I have learned that I must join the tables so now my query looks like this:
$camp = Camp::where('camps.id', $camp_id)
->with(['athletes' => function ($q) use ($camp_id) {
$q->with(['kickoffs' => function ($q) use ($camp_id) {
$q->where('camp_id', $camp_id);
$q->orderBy('id', 'desc');
}])->join('kickoff_results', 'athletes.id', '=', 'kickoff_results.athlete_id')
->orderBy('kickoff_results.score', 'desc');
But this seems to be returning me the same thing. I feel like my results are more accurate with my first query, but the ordering is incorrect.
Any suggestions are greatly appreciated!
Create foreign key in the secondary table
and join the table as follows:
DB::table('leads')->select('sec_tbname.sec_tbfk','sec_tbname.join_pm','prm_tbname.prm_tbpm')
->join('pm_tbname','sec_tbname.sec_tbfk','=','pm_tbname.id')
->get();

the best way to exclude some data from a method in sails controller

I want's to exclude some data in some controller method and in other method i want's that data. I do it with forEach function right into method after finding that :
nine: function (req, res) {
Dore.find()
.limit(9)
.sort('createdAt DESC')
.populate('file')
.exec(function (err, sh) {
if (err) {
return res.negotiate(err);
} else {
console.log('before : ', sh);
sh.forEach(function (item, i) {
delete item.zaman;
});
console.log('after : ', sh);
return res.send(sh);
}
});
},
I want to know how possible to do that with finding and do not included ever in finding so we don't need to remove that again with forEach.
tanks
As #zabware say we have select method in Query option I try this format but do not work and return all data :
I try to use that with following format but don't working :
Model.find( {
where: {},
limit: 9,
sort: 'createdAt DESC'
},
{
select: [ 'id', 'createdAt' ]
} )
and
Model.find( {
where: {},
limit: 9,
sort: 'createdAt DESC',
select: [ 'id', 'createdAt' ]
} )
and
Model.find( {}, select: [ 'id', 'createdAt' ] )
Although toJson is really designed to solve the kind of problem you are facing, it will not help you, since in some actions you want to exclude certain fields and in others not.
So we need to select fields per query. Luckily there is a solution for this in waterline:
Dore.find({}, {select: ['foo', 'bar']})
.limit(9)
.sort('createdAt DESC')
.populate('file')
.exec(function (err, sh) {
console.log(err);
console.log(sh);
});
This is supported since sails 0.11 but not really documented. You can find it under query options here https://github.com/balderdashy/waterline-docs/blob/e7b9ecf2510646b7de69663f709175a186da10d5/queries/query-language.md#query-options
I accidentally stumbled upon it while playing with the debugger - Sails version 1.2.3
There is something like omit and You can put it into your find method call:
const user = await User.findOne({
where: {email : inputs.email},
omit: ['password']
}); //There won't be password field in the user object
It is a pity that there is no word about it in the documentation.

Laravel 5 Eloquent Condition With Pivot

I have the Following models relationship.
promotions: [id, title, description]
sectors: [id, name]
promotion_sector: [promotion_id, sector_id]
class Promotion extends Model {
public function sectors() {
return $this->belongsToMany('App\Sector');
}
}
I want to get the promotions which are in given sectors.
For example,
All the promotions in sector A and B
To get all sectors associated with a promotion.
Try this:
class Promotion extends Model {
public function sectors() {
return $this->belongsToMany('App\Sector', 'promotion_sector', 'promotion_id', 'sector_id');
}
}
To verify, try this in artisan tinker:
$pro = App\Promotion::find(1);
$pro->sectors;
$pro;
You will get the list of all sectors associated with Promotion with Id 1.
To do the opposite, that you have asked in the question.
You need to do this:
class Sector extends Model {
public function promotions() {
return $this->belongsToMany('App\Promotion', 'promotion_sector', 'sector_id', 'promotion_id');
}
}
To verify, try this in artisan tinker:
$sec = App\Sector::find(1);
$sec->promotions;
$sec;
You will get the list of all the promotions associated with sector with Id 1.
I don't know which type of relationship you are using. I presume it to be Many-To-Many Relationship.
So here's the code you can try:
$result = DB::table('promotion_sector')
->join('promotions', 'id', '=', 'promotion_sector.promotion_id')
->join('sectors', 'id', '=', 'promotion_sector.sector_id')
->select('sectors.name AS sector_name')
->get();
dd( $result );
And if you are asking for the input from the user:
$result = DB::table('promotion_sector')
->join('promotions', 'id', '=', 'promotion_sector.promotion_id')
->join('sectors', 'id', '=', 'promotion_sector.sector_id')
->where( 'sectors.name', '=', $request->input('name_of_the_field') )
->select('sectors.name AS sector_name')
->get();
dd( $result );

How to add "order by" on a Magento Query

I installed a script for magento. It allows to add comments on orders. So it shows ONE comment on order grid.
The problem is that it doesn't sort comment by "created_at" column. I don't know how to set the order.
This is the portion of code:
protected function _initSelect()
{
parent::_initSelect();
// Join order comment
$this->getSelect()->joinLeft(
array('ordercomment_table' => $this->getTable('sales/order_status_history')),
'main_table.entity_id = ordercomment_table.parent_id AND ordercomment_table.comment IS NOT NULL',
array(
'ordercomment' => 'ordercomment_table.comment',
)
)->group('main_table.entity_id');
return $this;
}
Thanks for your help.
protected function _initSelect()
{
parent::_initSelect();
// Join order comment
$this->getSelect()->joinLeft(
array('ordercomment_table' => $this->getTable('sales/order_status_history')),
'main_table.entity_id = ordercomment_table.parent_id AND ordercomment_table.comment IS NOT NULL',
array(
'ordercomment' => 'ordercomment_table.comment',
)
)->group('main_table.entity_id');
//Add ORDER BY
$this->getSelect()->order(array('ordercomment_table.created_at DESC'));
return $this;
}
Replace this line in the above existing function. Add an ORDER BY.
$this->getSelect()->order('ordercomment_table.created_at', 'DESC');