我在解决Laravel关系时遇到了一些麻烦。 在我的应用程序中,用户和想法之间存在一对多关系。 (用户可能有多个想法。 我正在使用阿登特。
这是我的用户模型:
使用 Illuminate''Auth''UserTrait;使用 Illuminate''Auth''UserInterface;使用照明''身份验证''提醒''可提醒特征;使用照明''身份验证''提醒''提醒界面;使用拉拉维尔书''阿登特''阿登特;类 User extensions Ardent 实现 UserInterface, RemindableInterface { 使用UserTrait,RemindableTrait; /** * 模型使用的数据库表。 * * @var字符串 */ 受保护$table ="用户"; /** * 从模型的 JSON 表单中排除的属性。 * * @var阵列 */ 受保护$hidden = 数组("密码", "remember_token"); 受保护$fillable = array('first_name', 'last_name', 'email', 'password'); 公共$validation错误; 公共$autoPurgeRedundantAttributes = 真; 公共$autoHashPasswordAttributes = 真; 公共$autoHydrateEntityFromInput = 真; 公共静态$passwordAttributes = 数组("密码"); 公共静态$rules = 数组( 'first_name' => '必需|之间:1,16', 'last_name' => '必需|之间:1,16', "电子邮件" => "必需|电子邮件|唯一:用户", "密码" => "必填|介于:6,100" ); 公共函数思想() { 返回$this->hasMany("想法"); } }
这是我的想法模型:
使用拉拉维尔书''阿登特''阿登特;类 想法扩展 热心 { /** * 模型使用的数据库表。 * * @var字符串 */ 受保护$table="想法"; 受保护的$fillable = 数组('标题'); 公共$validation错误; 公共$autoPurgeRedundantAttributes = 真; 公共$autoHydrateEntityFromInput = 真; 公共静态$rules = 数组( "标题" => "必填" ); 公共函数用户() { 返回 $this->属于To("用户"); }}
最后,这是我的控制器代码:
类 IdeasController 扩展 BaseController { 公共函数 postInsert() { $idea = 新想法; $idea->user()->associate(Auth::user()); if($idea->save()) { 返回响应::json(array( "成功" => 真的, 'idea_id' => $idea->id, '标题' => $idea->标题), 200 ); } 还 { 返回响应::json(array( "成功" => 假, '错误' => json_encode($idea->错误)), 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
}
}
起初,我试图在想法中设置user_id如下:
$idea->user_id = Auth::id();
然后我把它改成:
$idea->user()->associate(Auth::user());
但结果是一样的。
任何建议将不胜感激。
您不能在该方向上使用associate
,因为它只能用于belongsTo
关系。在您的情况下,一个想法属于用户,而不是相反。
我怀疑保存时存在错误,因为您创建了一个没有所需标题的想法,然后您尝试通过调用 $idea->errors
来获取错误,而它应该是$idea->errors()
的。
associate
将处理belognsTo
关系,在您的事业中,您必须使用的是附加相关模型。请参阅文档中有关附加相关模式的更多信息。