我在解决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'); } }
And here's my Idea model:
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'); } }
Finally, here's my controller code:
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() throws the error:
{
"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());
但是结果是一样的。
任何建议将不胜感激。
最佳答案
您不能在该方向上使用associate
,因为它只能用于belongsTo
关系。在您的情况下,一个想法属于用户,而不是相反。
我怀疑保存时会出错,因为您创建的想法没有必需的标题,然后您尝试通过调用$idea->errors
来获取错误,而它应该是$idea->errors()
。
关于php - Laravel/Ardent-在save()上,错误: Relationship method must return an object of type Illuminate,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27710620/