Home Database Relationships in Laravel
Reply: 0

Database Relationships in Laravel

user1715
1#
user1715 Published in April 20, 2018, 10:49 am

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.

You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO