Laravel 4 -通过hasMany关系插入


Laravel 4 - Insert through hasMany relationship

这是我的模型关系…

class User extends Eloquent {
    public function loginLog(){
        return $this->hasMany('LoginLog');
    }
}
class LoginLog extends Eloquent {
    public function user(){
        return $this->belongsTo('User');
    }
}

当我在数据库中插入数据到login_logs表时,所有数据都正确输入,但它没有插入用户的id到user_id (laravel期望这一点)。

这是我如何插入到login_logs

$user->loginLog()->insert(array(
    'user_id'       => $user->id, //I could put it here, but then what is the point in a relationship?
    'email'         => $user->email,
    'ip_address'    => Request::getClientIp(),
    'country_code'  => $country_code,
    'status'        => $status,
    'created_at'    => Helper::dateTimeNow()
));

您必须附加用户。

在文档中http://laravel.com/docs/eloquent inserting-related-models

更新:

重读你的问题,我认为你想先通过他们的id找到用户,因为你在做$user->loginLog()->insert而不是$loginLog->insert

尝试链接它:$user::find($theIDYouWant)->loginLog()->insert