一直在学习laravel 4天,我试图修复这个错误2个小时,我仍然无法解决它 . 我可以节省一对多的关系,但我无法检索数据我认为这种关系有问题 . 我试图使用这一行检索用户的帖子,但我得到的结果不是空用户,而是帖子上的空结果 . 在类别和帖子上发生同样的事情,这是多对多关系,但我不能保存很多对很多 .
$users = User::with('posts')->get();
当我使用此错误时,我得到一个错误
未定义属性:Illuminate \ Database \ Eloquent \ Collection :: posts()
$users = User::where('user_id','=','2')->get();
$posts = $users->posts()->get();
继承我的用户模型
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $primarykey = 'user_id';
protected $table = 'users';
public function posts(){
return $this->hasMany("App\Post");
}
}
继承人我的帖子模特
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $primarykey = 'id';
protected $table = 'posts';
public function post_validation_rules(){
return [
'post_title' => 'required|min:5|unique:posts',
'post_body' => 'required'
];
}
public function user(){
return $this->belongsTo("App\User");
}
public function categories(){
return $this->belongsToMany('App\Category', 'category_id', 'category_id');
}
}
分类发布
class Category extends Model
{
protected $primarykey = 'category_id';
protected $table = 'categories';
public function posts(){
return $this->belongsToMany('App\Post', 'post_id', 'id');
}
}
Database
Posts Table
id
user_id
post_title
post_body
createad_date
updated_date
Users Table
user_id
username
email
pass
createad_date
updated_date
2 回答
尝试声明具有表之间关系的字段,例如:
$this->hasMany(App\Post::class, 'user_id', 'user_id');
Laravel正在用户表中搜索字段
id
但它不存在 . 所以用这种方式你会告诉它你看的字段是user_id
您只能在单个对象上调用关系,而不能在整个集合上调用关系 .
$users
是User
对象的集合 .如果需要单个用户对象,请使用
first()
函数获取匹配的第一个User
对象 .Update: 要直接在用户对象中获取帖子,您需要使用
with
函数: