Get a field from another table in eloquent model as an attribute with a if logic - laravel

Laravel > models >
In a table I have a list of files and an attribute that can be override with a value stored on another table
file_index (id, ..., code)
file_index_override(id, file_index_id, override_code)
In the file_index model, I would like to have an attribute that take the override_code if exists and the code if not. This structure is needed to run some groupBy on it.
At the moment I did
public function getCodeAnyAttribute() {
return FileIndexOverride::whereFileIndexId($this->id)->first() ?
FileIndexOverride::whereFileIndexId($this->id)->first()->override_code : $this->code;
}
But it does a single sql order on each lines, which cost a lot!
Is there a way using the power of eloquent?

Related

how to get data from a pivot table in a query at a controller

I have created a query in function at the controller where I want to get data from a pivot table based on the value sent using jquery.how can i create a function to get the values of the id associated with the selected house id in the controller.i have tried this but i get an error
$rentalcategoryhouses=Rental_house::whereIn('rentalcat_id',$rentalcategorydetails['catids'])
->with('housetags')->where('tag_id',$data['rentaltag'])->get();
the housetags here is the belongstoMany function in the house model that associates the houses with the tags.
function housetags(){
return $this->belongsToMany(Rental_tags::class,'rentalhouse_tags','rental_id','tag_id');
}
i want to get all the houses associated with the specific tag_id using a query in the controller.
this answer here solved my bug solution

Does eloquent pivot tables work for multi-word table names?

I have two multi-word models, let's call them FunkyModel and AnotherModel.
Will creating a pivot table named another_model_funky_model work?
The docs and examples I've come across all use single word model names like this: model A - User, model B - Address, and pivot table will then be address_user.
If you dive into the source code of the BelongsToMany relation function, you'll find that if you haven't provided a $table, the code will execute the function joiningTable. This uses the current model and the passed related class, snake cases the names and then puts them in alphabetical order of each other.
Simply said, no matter if you have a single word or a couple, the result will always be the 2 classes snaked, in alphabetical order. Note that the alphabetical order is applied by the default php sort.
Examples:
Department + Occupation > department_occupation
AwesomeModel + LessInterestingModel > awesome_model_less_interesting_model
Role + UserPermission > role_user_permission
You can even try and see what the auto-generated name is by simply calling the following:
(new Model)->joiningTable(OtherModel::class, (new OtherModel));
Yes it would work, you can also name it whatever you want, you just need to declare the table name in the relation (same goes for the foreign keys)
class FunkyModel
{
public function anotherModels()
{
return $this->belongsToMany(AnotherModel::class, 'pivot_table_name', 'funky_model_id', 'another_model_id');
}

changing a query result value according to wherehas condition in laravel

I am using laravel
I want to change the value of a column according to a specific condition.
if a condition is satisfied in wherehas then change the value of specific column to 1 let's say.How could i do it.
if i can call a function in the model inside the wherehas function to change the value how could I do it ??
i can iterate the result set using a 2 for loops and change it, however I want to decrease the complexity by changing the value while retrieving the data
Course::with('stages','stages.levels')->whereHas('stages.levels', function($query)use ($levelsarray){
$query->wherenotIn('id', $levelsarray);
here I want to change a column value in table levels
})->first();
Here is a general way,
Assuming you have Three models, Course, Stage, Level
When you are retrieving data from Level model, add an accessor,
For more info click here.
Eg:
On Level.php model,
public function getColumnNameAttribute($value) // replace ColumnName with column name
{
//write application logic here.
return $value;
}

how to make relation between table and array of ids from another table laravel

i have 2 tables, stores and products
stores table has field called products_ids
in this case i am saving the products in the stores by their ids in products_ids field as an array like this [1,2,3,4,5] i know it's not good practice to do it like this but this is the situation.
how can i make a relation in the model to achieve thing like this
Store::with('products')->get();
thanks
I don't know if this would work for you, but try it anyway:
in your Store model add the following:
public function products ()
{
return Product::whereIn('id', $this->products_ids)->get();
}

return separate result for each relation in many to many

Hi i have a many to many relationship with the following structure:
services
apps
service_app
I would like to have an eloquent query to return a separate result for each relationship(basically the pivot table). I have the following :
$all = App::with('services')->get();
this will return an app with nested services, I would like to have this return a separate result for each app-service combination along with data from the pivot table. how is this possible using eloquent?
It's a bit strange, but it can easily be done if you don't think of the pivot table as a pivot table, but as an AppService.
So what you can do is create a model for it, probably named AppService. In that model, you would then have 2 belongsTo() relationships. One for App and one for Service.
Then you can query your pivot table directly and use those relationships to get what you need.
$appServices = AppService::all();
foreach($appServices as $appService) {
echo $appService->app->description;
echo $appService->service->description;
}

Resources