Laravel has one through not returning correctly. always returning the first ID - laravel

I have a table that looks like this
ContractorDocuments Documents Documents_Category
user_id id id
documents_id documents__category_id name
I tried the following in my ContractorDocuments Model however it is always returning the first Document Category only.
public function Documents_Category() {
return $this->hasOneThrough(Documents_Category::class, Documents::class, 'documents__category_id', 'id', 'documents_id','documents__category_id');
}
documents__category_id == foreign key on Documents Table
id = foreign key on owners table(Documents_Category)
documents_id = local key on owners table(ContractorDocuments)
documents__category_id = local key on Documents table
Would appreciate any help. Thank you!

From ContractorDocuments to Documents_Category, you don't need hasOneThrough relationship since ContractorDocuments can only have one Documents_Category through belongsTo().
// ContractorDocuments model
public function documents()
{
return $this->belongsTo(Documents::class, 'documents_id');
}
And
// Documents model
public function documents_category()
{
return $this->belongsTo(Documents_Category::class, 'documents__category_id');
}
You can just call
$contractorDocuments->documents->documents_category;

Related

select data no repeat in pivot table

I have 2 table and 1 pivot table which I use as table Historical, the column 'dateChange' indicated the store where is the employee, because I use Orderby ('dateChange','DESC'). All is ok, however how can I FILTER the results in my controller? without REPEAT records?.
I need to show all the employees that belong to a unique store. I repeat again: I use 'dateChange' for I know the last store. help me, please. Thanks
Pivot Table (employee_store)
FK_idStore
FK_idEmployee
dateChange
Table Employee
idEmployee
Name
Table Store
idStore
nameStore
direction
Model
public function employee(){
return $this->belongsToMany(employee::class,'employee_store', 'fk_idStore','fk_idEmployee')
->withPivot('dateChange')->orderBy('dateChange','DESC');
Controller
$store= Store::findOrFail($id)->employee
return $store
You have to change
public function employee(){
return $this->belongsToMany(employee::class,..
to
public function employees(){
return $this->belongsToMany(Employee::class,..
you should use eager loading:
in your Controller
$store= Store::findOrFail($id)->with('employee')->get();
return $store;
more details in:
https://laravel.com/docs/7.x/eloquent-relationships#eager-loading
To get the last record of each employee in each store, use:
public function employee(){
return Employe_Store::all()->groupBy('fk_idEmployee')->max('dateChange');
}

Selecting specific column in ORM relationship Laravel 5.5

I have an order table with a primary key id and another table trips. I trip can have many orders. I have defined the relationship in this way
public function orders_currency() {
return $this->hasMany('App\Order', 'trip_id', 'id')->select('id', 'converted_currency_code');
}
Although I know that, I have to select id of the order table in order to get the result, that's why I am mentioning to select the id of the order table.
Despite this, I am getting the orders_currency index empty. Which angle am I missing in this case?
Any clue will be appreciated.
Did you set up the model correctly?
You'd do something like this in your model script I suppose
class Trips extends Model
{
public function orders() {
return $this->hasMany('Order');
}
I got the solution by doing this way
public function orders_currency() {
return $this->hasOne('App\Order', 'trip_id', 'id')
->select('trip_id','converted_currency_code');
}
I had to select referencing key in this case.

Laravel Eloquent Nested Relationships. Storing rows in controller variable

I have some working queries that are not ideal and I'd like to try perform them the Eloquent way to tidy it up.
I think I've got the relationships defined correctly but I can't figure out how to write the queries and store them in variables in the controller. I need to return these variables back to the view because I json encode them for use in JavaScript.
Here's what I have in my controller:
public function show($idProject)
{
$project = ProjectsModel::with('user')->where('idProjects','=',$idProject)->first();
$objsettings = ObjSettingsModel::where('idObjSettings','=',$project['ObjSettingsID1'])->first();
$obj = ObjModel::where('idObjs','=',$objsettings['Objs_idObjs'])->first();
return view('project')->with('project',$project)->with('obj',$obj)->with('objsettings',$objsettings);
}
The naming conventions are a bit off so here's what this does.
I pass the $idProject to the controller from a link on my index page where I've looped through and paginated all rows from the Projects table.
The first query finds the project row where it's id (idProjects) matches the variable passed from the index page via the link (idProject). I've also successfully pulled the related user row from the user table using an eloquent relationship.
The next query pulls from an ObjSettings table which stores a number of settings values for an object which is shown on the page. I match the idObjSettings column of the ObjSettings table to the previously pulled $project['ObjSettingsID1'] which is essentially the foreign key in the projects table. There can be several ObjSettings for each Project.
The 3rd query pulls from the Obj table which stores details about an object. These are static details on objects such as name or size for example. I match the idObjs column to the previously pulled $objsettings['Objs_idObjs'] which is the foreign key in the ObjSettings table. One Obj can have many ObjSettings which are used in other Projects.
Here's how I'm passing the php variables to JS:
<script>var obj = #json($obj);</script>
<script>var objsettings = #json($objsettings);</script>
Here are my relationships
ProjectsModel
public function user()
{
return $this->belongsTo('App\User', 'Username', 'id');
}
public function objsettings()
{
return $this->hasMany('App\ObjSettingsModel', 'idObjSettings', 'ObjSettingsID1' );
}
ObjSettingsModel
public function objs()
{
return $this->belongsTo('App\ObjsModel', 'Objs_idObjs', 'idObjs');
}
public function projects()
{
return $this->belongsTo('App\ProjectsModel', 'ObjSettingsID1', 'idObjSettings' );
}
ObjModel
public function objsettings()
{
return $this->hasMany('App\ObjSettingsModel', 'idObjs', 'Objs_idObjs');
}
I've tried a whole range of queries such as:
$project = ProjectsModel::with('user')->with('objsettings.objs')->where('idProjects','=',$idProject)->first();
$objsettings = $project->objsettings;
$obj = $project->objsettings->objs;
but I keep running into issues such as "Property [objs] does not exist on this collection instance." I suppose I'm returning multiple rows in this case? Any help would be appreciated.
You need to loop through objsettings
$project = ProjectsModel::with('user')->with('objsettings.objs')->where('idProjects','=',$idProject)->first();
$objsettings = $project->objsettings;
foreach($objsettings as $objsetting){
$objs = $objsetting->objs;
}

Laravel hasManyThrough, with belongs to between the other two models

Not sure how clear is the question title, I will try to elaborate:
Tables:
repairs (Model: Repair):
id
id_supplier
id_store
suppliers (Model: Supplier):
id
store (Model: Store):
id
Relations:
Repair:
public function supplier() {
return $this->belongsTo('App\Supplier', 'id_supplier');
}
Supplier:
public function repairs() {
return $this->hasMany('App\Repair', 'id_supplier');
}
Store:
public function repairs() {
return $this->hasMany('App\Repair', 'id_store');
}
What i need from here is to get the collection of all suppliers a given store worked with, through the repairs that were made there, so my first thought it was hasManyThrough, but no ideia what to pass as 4ยบ parameter:
Store:
public function suppliers() {
return $this->hasManyThrough('App\Supplier', 'App\Repair', 'id_supplier', '<NO IDEIA WHAT'S HERE>');
}
What am I missing? Is this the right way?
I think you can't use HasManyThrough here. Try something like this in your code:
$store = Store::with('repairs.supplier')->find($id_store);//eager load
$repairs = $store->repairs->pluck('supplier');//get array of suppliers id
$suppliers = (new Collection($repairs))->unique();//get unique collection of suppliers (without duplicates)
where $id_store is id of store which suppliers you want to get

Use a different column on a many-to-many relationship in Laravel 4

I've got a situation in a project where I need to form a relationship between a primary key on one table and an indexed column (not the primary key) on another. Here's a sample of the database layout:
courses table
id
level
resources table
id
courses_resources table
course_level
resource_id
In my CourseResource model I have the following:
public function courses(){
return $this->belongsToMany('Course', 'courses_resources', 'resource_id', 'course_level');
}
Which works fine.
Then in my Course model I have:
public function resources(){
return $this->belongsToMany('CourseResource', 'course_resources', 'course_level', 'resource_id');
}
Which doesn't work. When I look at the last query performed on the database, it appears Laravel is searching the course_level column using the course's ID. That makes sense, but is there any way to use the level column for this relationship?
Eloquent BelongsToMany depends on PKs, so there is no way to do that with its methods.
You need custom relation object for this, that will check for given field, instead of primary key.
A quick and hacky solution would be this:
// Course model
public function getKey()
{
$relation = array_get(debug_backtrace(1, 2), '1.object', null);
if (method_exists($relation, 'getForeignKey')
&& $relation->getForeignKey() == 'courses_resources.course_level')
{
return $this->getAttribute('level');
}
return parent::getKey();
}
However if you would like to use it in production, do some extensive testing first.

Resources