我正在尝试使用Laravel雄辩的关系创建,但我收到此错误
Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation
这就是我在控制器中尝试做的事情
$data = $request->all();
$company = Company::create([
'name' => $data['name'],
'description' => $data['description'],
]);
$company->members->create([
'name' => $data['name'],
'email' => $data['email'],
'status' => $data['status'],
'password' => bcrypt($data['password']),
]);
这是我的公司模式
class Company extends Model
{
protected $fillable = [ 'name', 'description'];
public function members(){
$this->hasMany('App\User');
}
public function reports(){
$this->hasMany('App\Report');
}
}
这是我的用户模型
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'password', 'company_id','status',
];
protected $hidden = [
'password', 'remember_token',
];
public function company(){
$this->belongsTo('App\Company');
}
这就是我遇到的错误
(1/1) LogicException
Relationship method must return an object of type
Illuminate\Database\Eloquent\Relations\Relation
in HasAttributes.php (line 403)
at Model->getRelationshipFromMethod('members')
in HasAttributes.php (line 386)
at Model->getRelationValue('members')
in HasAttributes.php (line 316)
at Model->getAttribute('members')
in Model.php (line 1262)
at Model->__get('members')
in AdminController.php (line 48)
at AdminController->addCompany(object(Request))
at call_user_func_array(array(object(AdminController), 'addCompany'), array(object(Request)))
in Controller.php (line 55)
at Controller->callAction('addCompany', array(object(Request)))
in ControllerDispatcher.php (line 44 )
如何解决此错误?
答案 0 :(得分:8)
你忘了像这样回归关系:
public function company(){
return $this->belongsTo('App\Company');
}
public function members(){
return $this->hasMany('App\User');
}
public function reports(){
return $this->hasMany('App\Report');
}