Hello i have below query
Deal::with(array('deal_category'=>function($query){
$query->select('name as dealcategory');
}))->get()
when i try to retrieve dealcategory it does not return any value. I have defined relationship in model like
Deal Model
public function deal_category()
{
return $this->belongsTo('App\DealCategory', 'deal_category_id', 'id');
}
And Deal category model like
public function deals(){
return $this->hasMany('App\Deal','deal_category_id');
}
can anyone help how can i get categoryname?
You have to select the primary key to retrieve the necessary results.
Deal::with(array('deal_category'=>function($query){
$query->select('id', 'name as dealcategory');
}))->get()
Use facade DB.
You can try something like this:
DB::table('deal as d')
->join('deal_category as dc', 'd.id', '=', 'dc.deal_id')
->select('d.name as dealname', 'dc.categoryname')
->get();
Related
Probably my mistake but i couldn't realize where my mistake is.
I have customer model which has schedule_registers() relation
public function schedule_registers()
{
return $this->hasMany('App\Models\ScheduleRegister', 'customer_id', 'id');
}
I also have ScheduleRegister model which has teacher() relation
public function teacher()
{
return $this->belongsTo('App\Models\User', 'teacher_id', 'id');
}
I get data in CustomerController like this (i don't use ->get() because i'm sending this data to datatable);
$customer_index = Customer::with([
'company',
'schedule_registers',
'schedule_registers.teacher',
]);
This query gives me that output;
https://jsonblob.com/915606370225766400
and when i try to use group by teacher_id and change query to this;
$customer_index = Customer::with([
'company',
'schedule_registers.teacher',
'schedule_registers' => function ($q) {
$q->groupBy('schedule_registers.teacher_id');
},
]);
output turns to this;
https://jsonblob.com/915605962518446080
In brief, when i try to use groupBy, i doesn't get any error, but get wrong output. If you could check outputs, when i use groupBy, some schedule_registers data becomes empty but some doesn't.
What is the right way to use groupBy in that situation?
I'm in need of help of figuring out how to get withCount() to work with nested relationships.
I have so far tried this
return CharityArea::with('campaigns.sponsor', 'campaigns.charityArea', 'campaigns.charityDetail')->withCount('campaigns.users')->where($matchTheseThings)->get();
Basically, I want to get the count of the users in the campaigns model.
The relationship on the CampaignsModel looks like this:
public function users(){
return $this->hasMany('App\UserPreferences', 'campaign_id', 'id');
}
The relationship to campaigns in CharityArea looks like this
public function campaigns(){
return $this->hasMany('App\Campaigns', 'charity_area_id', 'id');
}
Laravel throws and error saying that 'campaigns.users' is not found.
Any ideas on how else to do this?
Thanks.
You can use first set a ManyThrough relation in your CharityArea model.
function users()
{
return $this->hasManyThrough('App\UserPreferences', 'App\Campaigns');
}
Then you can call withCount() on it:
return CharityArea::with('campaigns.sponsor', 'campaigns.charityArea', 'campaigns.charityDetail')
->withCount('users')
->where($matchTheseThings)
->get();
I am trying to use Eloquent in Laravel in order to run a query. I am using the with() function in order to get the results from relationships, however this is always returning null.
This is my code:
Posts::query()
->select('id')
->with([
'author:id',
'category.images:url',
]);
Dumping the query using the getQueryLog() function and if I run the query inside of a SQL client with the same bindings I get a result back, however the response looks like this...
{
id: 1,
category: {
id: 1,
category_images: null
}
}
I've tried googling this issue and can't really find anything on it.
Thanks in advance.
Use your query like this:
Posts::query()->select('id')->with([ 'author', 'category' ])->get();
and in Posts model
public function author()
{
return $this->belongsTo('Authors::class', 'author_id', 'id')->select('id');
}
public function category()
{
return $this->belongsTo('Categories::class', 'category_id', 'id')->select('id', 'images.id', 'images.url');
}
You have to select your foreign keys in select statement to let Eloquent query your relationships, something like this:
Posts::query()
->select('id', 'author_id', 'category_id')
->with([
'author:id',
'category.images:url',
]);
I have some problem with a query in Laravel.
I want to create a filter query by column in server table but I don't know how to do this.
Need help to modify the following line:
$data = $video->files()->with('server')->get();
Model: server
public function files()
{
return $this->hasMany('App\Models\File', 'id', 'server_id');
}
Model: file
public function server()
{
return $this->belongsTo('App\Models\Server', 'server_id', 'id')->ordered();
}
My current query return this:
(but it returned all, I need return only FILE flitered by type = 6 which is server table) I don;t know how to do this. On screen below data about type server is on #relations array
Use WhereHas. Takes the relation name and a closure as a parameter, where you can define sub query like functionality with the relation.
$data = $video->files()->with('server')->whereHas('server', function ($query)
{
$query->where('type', '6');
})->get();
In my Database, I have:
tops Table
posts Table
tops_has_posts Table.
When I retrieve a top on my tops table I also retrieve the posts in relation with the top.
But what if I want to retrieve these posts in a certain order ?
So I add a range field in my pivot table tops_has_posts and I my trying to order by the result using Eloquent but it doesn't work.
I try this :
$top->articles()->whereHas('articles', function($q) {
$q->orderBy('range', 'ASC');
})->get()->toArray();
And this :
$top->articles()->orderBy('range', 'ASC')->get()->toArray();
Both were desperate attempts.
Thank you in advance.
There are 2 ways - one with specifying the table.field, other using Eloquent alias pivot_field if you use withPivot('field'):
// if you use withPivot
public function articles()
{
return $this->belongsToMany('Article', 'tops_has_posts')->withPivot('range');
}
// then: (with not whereHas)
$top = Top::with(['articles' => function ($q) {
$q->orderBy('pivot_range', 'asc');
}])->first(); // or get() or whatever
This will work, because Eloquent aliases all fields provided in withPivot as pivot_field_name.
Now, generic solution:
$top = Top::with(['articles' => function ($q) {
$q->orderBy('tops_has_posts.range', 'asc');
}])->first(); // or get() or whatever
// or:
$top = Top::first();
$articles = $top->articles()->orderBy('tops_has_posts.range', 'asc')->get();
This will order the related query.
Note: Don't make your life hard with naming things this way. posts are not necessarily articles, I would use either one or the other name, unless there is really need for this.
For Laravel 8.17.2+ you can use ::orderByPivot().
https://github.com/laravel/framework/releases/tag/v8.17.2
In Laravel 5.6+ (not sure about older versions) it's convenient to use this:
public function articles()
{
return $this->belongsToMany('Article', 'tops_has_posts')->withPivot('range')->orderBy('tops_has_posts.range');
}
In this case, whenever you will call articles, they will be sorted automaticaly by range property.
In Laravel 5.4 I have the following relation that works fine in Set model which belongsToMany of Job model:
public function jobs()
{
return $this->belongsToMany(Job::class, 'eqtype_jobs')
->withPivot(['created_at','updated_at','id'])
->orderBy('pivot_created_at','desc');
}
The above relation returns all jobs that the specified Set has been joined ordered by the pivot table's (eqtype_jobs) field created_at DESC.
The SQL printout of $set->jobs()->paginate(20) Looks like the following:
select
`jobs`.*, `eqtype_jobs`.`set_id` as `pivot_set_id`,
`eqtype_jobs`.`job_id` as `pivot_job_id`,
`eqtype_jobs`.`created_at` as `pivot_created_at`,
`eqtype_jobs`.`updated_at` as `pivot_updated_at`,
`eqtype_jobs`.`id` as `pivot_id`
from `jobs`
inner join `eqtype_jobs` on `jobs`.`id` = `eqtype_jobs`.`job_id`
where `eqtype_jobs`.`set_id` = 56
order by `pivot_created_at` desc
limit 20
offset 0
in your blade try this:
$top->articles()->orderBy('pivot_range','asc')->get();
If you print out the SQL query of belongsToMany relationship, you will find that the column names of pivot tables are using the pivot_ prefix as a new alias.
For example, created_at, updated_at in pivot table have got pivot_created_at, pivot_updated_at aliases. So the orderBy method should use these aliases instead.
Here is an example of how you can do that.
class User {
...
public function posts(): BelongsToMany {
return $this->belongsToMany(
Post::class,
'post_user',
'user_id',
'post_id')
->withTimestamps()
->latest('pivot_created_at');
}
...
}
You can use orderBy instead of using latest method if you prefer. In the above example, post_user is pivot table, and you can see that the column name for ordering is now pivot_created_at or pivot_updated_at.
you can use this:
public function keywords() {
return $this->morphToMany(\App\Models\Keyword::class, "keywordable")->withPivot('order');
}
public function getKeywordOrderAttribute() {
return $this->keywords()->first()->pivot->order;
}
and append keyword attribiute to model after geting and use sortby
$courses->get()->append('keyword_order')->sortBy('keyword_order');