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
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.