Laravel modal query - php

I am trying to get array of related model to my data and it returns null.
Code
public function collection()
{
return Product::with(['allBarcodes' => function ($query) {
$query->select('serial_number');
}])->get();
}
result
Also I tried pluck like $query->pluck('serial_number'); and result was
My real data
the data I suppose to receive is like
[{
"id":1,
"product_id":1,
"serial_number":"5245412185", // I only need this to be return as array
"sold":1,
"created_at":"2020-05-24T04:21:56.000000Z",
"updated_at":"2020-05-24T04:21:56.000000Z"
}]
Any idea?

When you are doing this $query->select('serial_number'); you are only selecting serial_number and not the column that connects both the modals i.e. product_id inside barcodes table.
Do this.
$query->select('product_id', 'serial_number');. However this will return 2 columns. If you want just one then you will have to use collection transform.
$products = $products->map(function ($product) {
$product->allBarcodes->transform(function ($q) {
return $q->serial_number;
});
return $product;
});
Keep me posted in the comments below.

Related

Datatables: how to preserve id when sorting through a relation from another table (yajra, laravel)

I'm using datatables from yajra datatables and I have a problem.
I have a datatable where I obtain certain columns from other tables, for example the column "customer" is obtained through a relation from another table
But when I press the sort by customer button, the IDs change to the ID of the table where the relation belongs
This generates errors in the buttons that I have on the right since these IDs do not exist in the "meos" table, only in the "locations" table that is in the relation
How can I make it sort while keeping the same ID it had?
I want to always keep as order criteria the ID of the table I am with, which is the "meos" table belonging to the "meo" class
This is my query
public function query()
{
$languageId = Auth::user()->language_id;
return Meo::with(['businessType' => function ($query) use ($languageId) {
$query->with(['businessTypeDescriptions' => function ($subQuery) use ($languageId) {
$subQuery->where('language_id', '=', $languageId);
}]);
}])->with('location');
}
this is my function getcolumns
protected function getColumns()
{
return [
Column::make('id')->addClass('text-center')->title(__('digestReport.columns.id')),
Column::make('location.location_name')->addClass('text-center')->title(__('digestReport.columns.customer')),
Column::make('businessType')->addClass('text-center')->title(__('digestReport.columns.business_type'))->searchable(false),
Column::computed('action')->exportable(false)->printable(false)->width(160)->addClass('text-center')->title(__('digestReport.columns.actions')),
];
}
please, I need help.
Thanks :)
Try below code. Add ->select() statement
public function query()
{
$languageId = Auth::user()->language_id;
return Meo::with(['businessType' => function ($query) use ($languageId) {
$query->with(['businessTypeDescriptions' => function ($subQuery) use ($languageId) {
$subQuery->where('language_id', '=', $languageId);
}]);
}])->with('location')->select('meo-table.*');
}
Replace meo-table with your database table for Meo::class

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;
});

Laravel sub query not removing results when using a nested with

I have a 'user' table that has a pivot table for services that a user offers:
// App\User
public function services()
{
return $this->hasMany('App\ServiceUser');
}
On the ServiceUser model I then have another relationship to get the service information:
public function service()
{
return $this->hasOne('App\Service', 'id');
}
When fetching a team (using Laravel Spark) the query I am using is:
Team::with('users')->withUserCustomerServices()->where('id', $teamId)->first();
The scope for this query is in the Team model:
public function scopeWithCustomerServices($query)
{
$query = $query;
$query->with('users.services');
$query->with(['users.services.service' => function($q) {
$q->where('visible_to_customers', 1);
}]);
return $query;
}
When outputting (using Vue.js):
{{ user.services.length }}
I get (in this example) 6 results returned. However, one of the services has a database field 'visible_to_customers' set to 0.
Initially I thought my query would work as expected and only return 5 services however it actually still returns them all, but doesn't return the relationship (service) if the field is 0.
How can I can I only return the pivot table result where the relationship has a certain field value?
EDIT
I have updated the query to use a whereHas on the first nested relation:
$query->with(['users.services' => function($q) {
$q->whereHas('service', function($q) {
$q->where('visible_to_customers', 1);
});
}]);
This works great, only returns the pivot table rows where the services table has a field value of 1 for visible_to_customers.
However, that doesn't fetch the related row itself.
If I then chain on:
$query->with(['users.services' => function($q) {
$q->whereHas('service', function($q) {
$q->where('visible_to_customers', 1);
});
}]);
$query->with(['users.services.service' => function($q) {
$q->where('visible_to_customers', 1);
}]);
It remains the same issue where it fetch all of the rows but then only the related rows where the field is 1.
Fixed this issue by using a where has on the first relationship that is the pivot:
$query->with(['users.services' => function($q) {
$q->whereHas('service', function($q) {
$q->where('visible_to_customers', 1);
})->with('service');
}]);
I then appended the ->with('service') to the end of the chain.

Laravel - Put all records together?

I want to get every 'stat' value from every record in where government_type = 'higher_government' but at the moment my code only gets the stats instances for the first government role it finds, how can I put together all of the stats in some sort of array?
$higherGovernment = Cache::remember('government.higher_government', 1, function() {
return GovernmentRole::where('government_type', 'higher_government')->first()->stats;
});
Stats relationship:
public function government_role()
{
return $this->belongsTo('App\Database\Website\Roleplay\GovernmentRole', 'government_id');
}
Government relationship:1
public function stats(){
return $this->hasMany('App\Database\Website\User\Roleplay', 'government_id');
}
Use pluck()->toArray()
GovernmentRole::where('government_type', 'higher_government')->pluck('stats')->toArray();
This code will return an array of stats properties.
You should be able to use the pluck() method from Eloquent's Collection. https://laravel.com/docs/5.3/collections#method-pluck
Change your query to something like:
GovernmentRole::where('government_type', 'higher_government')
->get()
->pluck('stats', 'government_id');
This will give you a collection containing government_id => stats.
If you want an array rather than a collection, simply add ->toArray()

Laravel 4 Advanced Where - Unknown Column

I have a query which looks like this:
$items = Item::live()
->with('location')
->where('last_location_id', Input::get('last_location_id'))
->get();
The background of this is...
2 tables: Items & Cars.
The live scope is:
public function scopeLive($query)
{
return $query->whereHas('basic_car', function($q)
{
$q->whereNotNull('id')->where('sale_status', 'Live');
});
}
This basically checks the cars table for a matching id to that of the items 'car_id' field and will run some where clauses on the cars table.
I now however want to check another field on the cars table, but using the Input::get('last_location_id') from the original query.
$items = Item::live()
->with('location')
->where('last_location_id', Input::get('last_location_id'))
->orWhere('ROW ON THE CARS TABLE' = Input::get('last_location_id'))
->get();
This does't work, then I tried:
$items = Item::live()
->with('location')
->where('last_location_id', Input::get('last_location_id'))
->orWhere(function($query)
{
$query->where('cars.Location', Input::get('last_location_id'));
})
->get();
Which results in an unknown column 'cars.Location' error.
My next test was to create another scope:
public function scopeLiveTest($query)
{
return $query->whereHas('basic_car', function($q)
{
$q->whereNotNull('id')->where('sale_status', 'Live')->where('Location', 1); // hardcoded ID
});
}
And replacing the live() scope with that works but I dont get the affect of the orWhere in the query itself and I also cannot specify a ID from the Input.
How can I do this?
You can pass a parameter to scope like this:
$items = Item::liveAtLocation(Input::get('last_location_id'))
->orWhere(function( $query ) { // to get the OR working
$query->live()
->with('location')
->where('last_location_id', Input::get('last_location_id'));
})
->get();
And for the scope:
public function scopeLiveAtLocation($query, $location_id)
{
return $query->whereHas('basic_car', function($q) use ($location_id)
{
$q->whereNotNull('id')->where('sale_status', 'Live')->where('Location', $location_id);
});
}

Categories