Home Database Relationships in Laravel

# Database Relationships in Laravel

PhpNewbie
1#
PhpNewbie Published in 2017-12-07 20:33:07Z
 I have Author model that looks like this: hasOne('App\Role'); } }  And Role model that looks like: role->pareigos; return view('authors', ['role' => $role]); } }  But I get error like: "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'roles.author_id' in 'where clause' (SQL: select * from roles where roles.author_id = 5 and roles.author_id is not null limit 1) Where does the author_id even come from? I have two tables in database, first one is authors that has id,firstname,lastname,role_id. Second one is roles that has two rows - id and pareigos. So I use this command: $role = Author::find(5)->role->pareigos;  To find Author by id (5) and check his role_id in roles table and return pareigos if the ID's matches. Don't know if I have described the problem clearly - if not, just let me know I eill add more details.
lagbox
2#
 Your relationship is setup incorrectly. The table that has the key pointing to another table, belongs to that other table. class Author ... { public function role() { return \$this->belongsTo(Role::class); } ...  This will want to look for a role_id key on authors table. By default, unless you pass more arguments to override it, Laravel uses the calling function name to decide the name of the foreign key for belongsTo relationships. [ method is named role, so it knows to look for role_id ... methodname + _id ]