让我的Laravel关系搞定,我遇到了一些麻烦 . 在我的应用程序中,用户和想法之间存在一对多的关系 . (用户可能有多个想法 . )我正在使用Ardent .
这是我的用户模型:
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
use LaravelBook\Ardent\Ardent;
class User extends Ardent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('password', 'remember_token');
protected $fillable = array('first_name', 'last_name', 'email', 'password');
public $validation_errors;
public $autoPurgeRedundantAttributes = true;
public $autoHashPasswordAttributes = true;
public $autoHydrateEntityFromInput = true;
public static $passwordAttributes = array('password');
public static $rules = array(
'first_name' => 'required|between:1,16',
'last_name' => 'required|between:1,16',
'email' => 'required|email|unique:users',
'password' => 'required|between:6,100'
);
public function ideas()
{
return $this->hasMany('Idea');
}
}
这是我的Idea模型:
use LaravelBook\Ardent\Ardent;
class Idea extends Ardent {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'ideas';
protected $fillable = array('title');
public $validation_errors;
public $autoPurgeRedundantAttributes = true;
public $autoHydrateEntityFromInput = true;
public static $rules = array(
'title' => 'required'
);
public function user()
{
return $this->belongsTo('User');
}
}
最后,这是我的控制器代码:
class IdeasController extends BaseController {
public function postInsert()
{
$idea = new Idea;
$idea->user()->associate(Auth::user());
if($idea->save())
{
return Response::json(array(
'success' => true,
'idea_id' => $idea->id,
'title' => $idea->title),
200
);
}
else
{
return Response::json(array(
'success' => false,
'errors' => json_encode($idea->errors)),
400
);
}
}
}
$ idea-> save()抛出错误:
{
"error": {
"type": "LogicException",
"message": "Relationship method must return an object of type Illuminate\\Database\\Eloquent\\Relations\\Relation",
"file": "\/var\/www\/3os\/vendor\/laravel\/framework\/src\/Illuminate\/Database\/Eloquent\/Model.php",
"line": 2498
}
}
起初,我试图在Idea中设置user_id,如下所示:
$idea->user_id = Auth::id();
然后我把它改成:
$idea->user()->associate(Auth::user());
但结果是一样的 .
任何建议将不胜感激 .
2 回答
associate
将处理belognsTo
关系,在您的事业中您必须使用的是附加相关模型 . 有关在documentation中附加相关模式的详细信息,请参阅 .您不能在该方向上使用
associate
,因为它只能用于belongsTo
关系 . 在您的情况下,一个想法属于用户而不是相反 .我怀疑保存时出错,因为你创建了一个没有所需 Headers 的想法,然后你试着通过调用
$idea->errors
来获取错误,而它应该是$idea->errors()
.