如何使用Laravel Eloquent加入?

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 ?

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;

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!

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