Home Database Relationships in Laravel
Reply: 1

Database Relationships in Laravel

PhpNewbie
1#
PhpNewbie Published in 2017-12-07 20:33:07Z

I have Author model that looks like this:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Author extends Model {
   public $timestamps = false;

   public function role()
   {
    return $this->hasOne('App\Role');
  }
}

And Role model that looks like:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Role extends Model {
   public $timestamps = false;
}

My AuthorController.php looks like:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Author;

class AuthorController extends Controller
{
  public function index(){
    $role = Author::find(5)->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#
lagbox Reply to 2017-12-07 20:44:24Z

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 ]

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.337749 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO