我正在使用 laravel 4.2 。
我有两个模型如下:
class User extends Eloquent{
protected $table = 'users';
public function user_card_details(){
return $this->hasMany('User_card_details');
}
}
并且
class User_card_details extends Eloquent {
protected $table = 'user_card_details';
public $timestamps = true;
public $softdeletes = true;
public function user(){
return $this->belongsTo('User')->first();
}
}
我可以使用以下方式保存关系记录:
$user_card_details = new User_card_details();
$user_card_details->card_number = Input::get('card_number');
$user_card_details->card_exp_month = Input::get('card_expires_m');
$user_card_details->card_exp_year = Input::get('card_expires_y');
$user_card_details->card_cvv = Input::get('card_cvv');
$user->user_card_details()->save($user_card_details);
到目前为止,它对我来说很好。
在save()
之后,我想要用user_details
填充用户对象。
因此,如果我想使用这些属性,我可以使用它:
echo $user->user_card_details->card_number
;
但现在不行。
有什么建议吗?
由于
答案 0 :(得分:0)
您必须删除()
才能获得实际的模型或集合:
echo $user->user_card_details->card_number;
当您调用实际功能时,您将收到“查询”构建器的实例。
此外,在您尝试将其绑定到用户之前,您似乎没有保留$user_card_details
- 对象:
$user_card_details = new User_card_details();
$user_card_details->card_number = Input::get('card_number');
$user_card_details->card_exp_month = Input::get('card_expires_m');
$user_card_details->card_exp_year = Input::get('card_expires_y');
$user_card_details->card_cvv = Input::get('card_cvv');
$user_card_details->save(); //Added this line.
$user->user_card_details()->save($user_card_details);
更正确的方法是:
$user_card_details = [
'card_number' => Input::get( 'card_number' ),
'card_exp_month' => Input::get( 'card_expires_m' ),
'card_exp_year' => Input::get( 'card_expires_y' ),
'card_cvv' => Input::get( 'card_cvv' ),
];
$userCardDetailObj = $user->user_card_details()->create( $user_card_details );
现在,您的User_card_detail
- 实例将作为返回的对象提供。