I've created a one-to-many relationship between a Jobs Model and Permits model. I've recently discovered the awesome tool of Tinker so I've been using it to test my models. When I run Job::with('steps')->find(1); I get this error
Illuminate\Database\QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'steps.job_id' in 'where clause' (SQL: select * from `steps` where `steps`.`job_id` in (1))'
Here's my Job Model
public function steps ()
{
return $this->hasMany('MyfirstApp\Step');
}
Here's my Step Model
public function Job ()
{
return $this->belongsTo('MyFirstApp\Job');
}
I've already set up the foregin key in the Jobs Table so I'm not sure what the error can be. Any ideas?
Table Structure for reference
For your relationship, Job has many Steps, you have assigned wrong foreign key.
In your case steps table should contain job_id rather than job contains steps_id.
Solution:
Remove steps_id from job table.
Set job_id in steps table as a foreign key.
Try it
You are set wrong relationship on model
Job Model
public function steps ()
{
return $this->belongsTo('MyfirstApp\Step');
}
Step Model
public function Job ()
{
return $this->hasMany('MyFirstApp\Job');
}
Related
This issue happens for me on Backpack v5 and Laravel 8 (although I do reproduce it on Laravel 9 as well).
My issue happens when I have a setup similar to this one : https://backpackforlaravel.com/docs/5.x/crud-fields#manage-related-entries-in-the-same-form-create-update-delete
Just to clarify here:
Two models related by a 1-n relationship
Those models override their $primaryKey attribute (as their primary key is not "id")
the "parent" models CRUD that has a 'type' => 'relationship' with 'subfields' to add children through a "repeatable" type field
This is the error I get (with the Monsters and Stories example):
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id_story' in 'where clause'
select * from `monsters` where `monsters`.`story_id` = 5 and `monsters`.`story_id` is not null and (`id_story` is null) limit 1
The stack trace leads me to vendor\backpack\crud\src\app\Library\CrudPanel\Traits\Create.php:310
Here is how I reproduced it on the Backpack demo projet:
Install demo project following instructions here :https://backpackforlaravel.com/docs/4.1/demo#demo-installation
Rename monsters primary key in table to id_monster and stories primary key to id_story
Add the $primaryKey overrides on corresponding models like so:
protected $primaryKey = 'id_monster'; // In Monster.php
protected $primaryKey = 'id_story'; // In Story.php
Add correct "foreignKey" parameters to relation method like so:
// In Story.php
public function monsters()
{
return $this->hasMany(\App\Models\Monster::class, 'story_id');
}
// In Monster.php
public function story()
{
return $this->belongsTo(\App\Models\Story::class, 'story_id');
}
Now add a story with a monster through the Crud panel and you should reproduce the error.
I'm thinking I'm probably missing something but I just can't figure it out. I'm pretty sure the relations are properly defined and I'm wondering if it's not a bug in Backpack.
Thanks for your help !
UPDATE
This is indeed an issue that has been reported here
I'm seeing that you are using "story_id" in both relations (Story.php and Monster.php).
In Story.php you should use :
public function monsters()
{
return $this->hasMany(\App\Models\Monster::class, 'story_id');
}
And In Monster.php you should use :
public function story()
{
return $this->belongsTo(\App\Models\Story::class, 'monster_id');
}
Also be careful that when you are trying to set relationships in migrations and in models, you are setting correct foreign keys both in migration and models.
I'm creating an application wherein users can be assigned to multiple organisations, and organisations can have many users - many-to-many relationships.
I want to be able to do something like this:
$user->organisations()->get() as well as $organisation->users()->get()
I have a users table...
I have an organisations table...
Uh! users-organisations, organisations-users!
and I have a user_orgs pivot/mapping/etc. table
Note
The user_orgs table has an org_id field, and a user_id field.
Eloquent assumes and expects organisation_user - but that is not what I have named my table, nor do I want to rename.
I set up the following
App/Organisation.php
public function users(){
return $this->belongsToMany("App\User");
}
and on user:
App/User.php
public function organisations(){
return $this->belongsToMany("App\Organisation");
}
And then I test this:
Route::get('/test-route', function(){
$u = App\User::first();
return $u->organisations()->get();
});
and get the following error:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'db.organisation_user' doesn't exist (SQL: select organisations.*, organisation_user.user_id as pivot_user_id, organisation_user.organisation_id as pivot_organisation_id from organisations inner join organisation_user on organisations.id = organisation_user.organisation_id where organisation_user.user_id = 1)
The two questions in my mind are, one; how do I specify to Eloquent, to use user_orgs instead of assuming organisation_user, the same way I can override the tableName or primaryKey on a model? Two: how can I specify the foreignKey column, such that it uses user_orgs.org_id and not user_orgs.organisation_id?
But please do suggest alternatives.
Thanks all, in advance.
You can set the name of the pivot table by passing it as the second argument to the belongsToMany() relationship, like below:
public function users(){
return $this->belongsToMany("App\User", "user_orgs");
}
public function organisations(){
return $this->belongsToMany("App\Organisation", "user_orgs");
}
Documentation:
https://laravel.com/docs/5.8/eloquent-relationships#many-to-many
As mentioned previously, to determine the table name of the relationship's joining table, Eloquent will join the two related model names in alphabetical order. However, you are free to override this convention. You may do so by passing a second argument to the belongsToMany method.
I have 3 tables in a database
Transaction {'id','bill_id','remark'}
Bills {'id','third_party','amount'}
ThirdParty {'id','company_name',remark}
The 'transaction' table has column bill_id coming from 'Bills' and Bills table has 'third_party' column which connected to ThirdParty table column -> 'id'
So here I am trying to fetch company_name using laravel eloquent relation
My Transaction model:
public function Bills()
{
return $this->hasOne('App\Bills','id','bill_id');
}
Bills:
public function third_party()
{
return $this->belongsTo('App\ThirdParty','third_party','id');
}
I am getting null value for company_name
Here is the query i am using
Transaction::with('Bills.third_party')->get();
And i have corrected in question (third_party_name) to company_name column name i wrote here was my old join query name which is visible in screenshot, basically i am trying to fetch company name.
Are you able to show all of your code? How does company_name get set to third_party_name?
You could probably also gain a lot by sticking to the laravel "conventions" or "suggested naming", this will give you a lot of functionality for free, and make your code easier to read, write and debug.
eg. Your relationship method names (Bills(), third_party()), but more importantly if you name your table fields in the "laravel way", you will get easier eloquent relationships as there will be no need to define the foreign keys etc.
I would be setting this up similar to:
Transaction {'id','bill_id','remark'}
Bills {'id','third_party_id','amount'} <- note the third_party_id
ThirdParty {'id','company_name',remark}
class Transaction extends Model
{
public function Bills()
{
return $this->hasOne('App\Bills');
}
}
class Bills extends Model
{
public function ThirdParty()
{
return $this->belongsTo('App\ThirdParty);
}
}
You should also define the inverse relationships.
It would be very beneficial to see the full code to see where the issue is.
I want to make a relation between my tables with belongToMany.
These are my three tables, that I want to connect.
fairkatert_task
-id
-user_id
-name
fairkatert_milestone
-id
-name
fairkatert_task_assign_milestone
-id
-milestone_id
-task_id
I use the belongToMany Method from Eloquent.
public function getTasks()
{
return $this->belongsToMany(
'App\Http\Models\Task',
'fairkatert_task_assign_milestone',
'milestone_id',
'task_id'
);
}
And i only get the following SQL Error Message:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'milestone_id' in 'where clause' (SQL: select * from `fairkatert_task` where `fairkatert_task`.`deleted_at` is null and (`milestone_id` is null))
But I think I've done everything right but,but can't my mistake.
Expanding on Josef's comment, you are looking directly at the answer - which you have acknowledged.
However you're struggling to understand:
I did, but i do not unterstand why it's looking for milestone_id in the "fairkatert_task" table.
Reading Laravels documentation on a belongsToMany relationship it states:
In addition to customizing the name of the joining table, you may also customize the column names of the keys on the table by passing additional arguments to the belongsToMany method. The third argument is the foreign key name of the model on which you are defining the relationship, while the fourth argument is the foreign key name of the model that you are joining to:
return $this->belongsToMany('App\Role', 'user_roles', 'user_id', 'role_id');
Your relationship is:
public function getTasks()
{
return $this->belongsToMany(
'App\Http\Models\Task',
'fairkatert_task_assign_milestone',
'milestone_id',
'task_id'
);
}
The third argument is the foreign key name of the model on which you are defining the relationship
This means your third argument, milestone_id is trying to be found by fairkatert_task.
Oh my god i found my problem ...
I had in my controller still an old method, that i load
I can't figure out how to make aliases for my table column names such that I can use Laravel's Eloquent belongsTo() functionality.
I have a groups table and and an activities table. The activities table references the groups table by organization_id rather than groups_id.
How do I write belongsTo in my Activity model as the following doesn't work.
public function group()
{
return $this->belongsTo('App\Group', 'organization_id');
}
What I'd like to write is:
App\Activity->group
In the code you have pasted laravel will think that the organization id is the column in your activities table which your are using as foreign key what you should do is :
public function group()
{
return $this->belongsTo('App\Group', 'organization_id', 'id');
}
in the above code you will get all results where activies.id = groups.organization_id;
UPDATE by Tim Peterson
My original code works. I migrated my DB for something else so that must have fixed everything.