简体   繁体   中英

How to use join in 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 ?

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM