0

I have following two tables.

users - id,name,title
posts - id,author

where post.author = user.id

My Post model as follows.

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public function users()
    {
       return $this->belongsTo('App\User');
    }
}

I use Project::find(1)->users

But it giving following error.

SQLSTATE[42S02]: Base table or view not found.

Can anyone please help ?

Robin Dirksen
  • 3,322
  • 25
  • 40
IshaS
  • 837
  • 1
  • 10
  • 31
  • 1
    Shouldn't it be: `Post::find(1)->users` ? – Daan May 30 '16 at 12:38
  • 1
    You need to read the [docs](https://laravel.com/docs/5.2/eloquent-relationships#one-to-one). By default, Laravel assumes the id would be `user_id` in the `posts` table. If you want to use the `author` column name, then you may override that in your `User` model. – Kirk Beard May 30 '16 at 12:40
  • @Daan yes it is.changed it.but not works. – IshaS May 30 '16 at 13:31
  • Thanks @Krik Bread. Is this the way? return $this->hasManyThrough('App\Post', 'author'); – IshaS May 30 '16 at 13:36

3 Answers3

1

You can change your code to this:

class Post extends Model
{
    public function user()
    {
       return $this->hasOne('App\User', 'id', 'author');
    }
}

This will get the user from the database by calling Post::find(1)->user->id.

I suggest to change users to user because a post can have only one author.

Hope this works!

Robin Dirksen
  • 3,322
  • 25
  • 40
0

This should change

Project::find(1)->users

to this

Post::find(1)->users

Read This

  1. Base table or view not found: 1146 Table Laravel 5
Community
  • 1
  • 1
Abdulla Nilam
  • 36,589
  • 17
  • 64
  • 85
0

Your Post model..

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public function users()
    {
       return $this->belongsTo('App\User', 'author');
    }
}

Now use it as..

Post::find(1)->users;

As because a post have only a single creator you can change the users method on Post model as user and use it as

Post::find(1)->user;
Parvez Rahaman
  • 4,269
  • 3
  • 22
  • 39