Laravel/Ardent - 在 save() 上,错误:关系方法必须返回 Illuminate 类型的对象

clo*_*e45 5 php relationships laravel eloquent

我在解决 Laravel 关系时遇到了一些麻烦。在我的应用程序中,用户和想法之间存在一对多的关系。(用户可能有多种想法。)我正在使用 Ardent。

这是我的用户模型:

使用 Illuminate\Auth\UserTrait;
使用 Illuminate\Auth\UserInterface;
使用 Illuminate\Auth\Reminders\RemindableTrait;
使用 Illuminate\Auth\Reminders\RemindableInterface;

使用 LaravelBook\Ardent\Ardent;

class User 扩展 Ardent 实现 UserInterface、RemindableInterface {

    使用 UserTrait、RemindableTrait;

    /**
     * 模型使用的数据库表。
     *
     * @var 字符串
     */
    受保护的 $table = '用户';

    /**
     * 从模型的 JSON 形式中排除的属性。
     *
     * @var 数组
     */
    protected $hidden = array('password', 'remember_token');
    protected $fillable = array('first_name', 'last_name', 'email', 'password');

    公共 $validation_errors;
    公共 $autoPurgeRedundantAttributes = true;
    公共 $autoHashPasswordAttributes = true;
    公共 $autoHydrateEntityFromInput = true;

    public static $passwordAttributes = array('password');

    公共静态 $rules = 数组(
        'first_name' => 'required| between:1,16',
        'last_name' => 'required| between:1,16',
        'email' => 'required|email|unique:users',
        '密码' => '必需|介于:6,100'
    );

    公共功能的想法()
    {
        返回 $this->hasMany('Idea');
    }   
}

这是我的想法模型:

使用 LaravelBook\Ardent\Ardent;

class Idea 扩展了 Ardent {

    /**
     * 模型使用的数据库表。
     *
     * @var 字符串
     */
    受保护的 $table = 'ideas';

    protected $fillable = array('title');

    公共 $validation_errors;
    公共 $autoPurgeRedundantAttributes = true;
    公共 $autoHydrateEntityFromInput = true;

    公共静态 $rules = 数组(
        '标题' => '必填'
    );

    公共函数用户()
    {
        返回 $this->belongsTo('User');
    }
}

最后,这是我的控制器代码:

类 IdeasController 扩展 BaseController {

    公共函数 postInsert()
    {
        $idea = 新想法;

        $idea->user()->associate(Auth::user());

        if($idea->save())
        {
            返回响应::json(数组(
                '成功' => 真,
                'idea_id' => $idea->id,
                'title' => $idea->title),
                200
            );
        }
        别的
        {
            返回响应::json(数组(
                '成功' => 假,
                '错误' => 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
  }
}
Run Code Online (Sandbox Code Playgroud)

起初,我试图在 Idea 中设置 user_id ,如下所示:

$idea->user_id = Auth::id();
Run Code Online (Sandbox Code Playgroud)

然后我把它改成:

$idea->user()->associate(Auth::user());
Run Code Online (Sandbox Code Playgroud)

但结果是一样的。

任何建议将不胜感激。

low*_*nds 4

你不能在那个方向使用associate,因为它只能用在belongsTo关系上。就您而言,一个想法属于用户,而不是相反。

我怀疑保存时出现错误,因为您创建了一个没有所需标题的想法,然后尝试通过调用 来获取错误$idea->errors,而实际上应该是$idea->errors()。