【问题标题】:Laravel 4 - Insert through hasMany relationshipLaravel 4 - 通过 hasMany 关系插入
【发布时间】:2014-09-30 03:44:31
【问题描述】:

这是我的模特关系...

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()
));

【问题讨论】:

  • 因为您没有将插入 user_id 列值放入 loginLog() 插入查询?不过很困惑。

标签: php laravel laravel-4


【解决方案1】:

您必须附加用户。

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

更新:

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

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

【讨论】:

  • $user 已设置为找到的用户。但是,您的帖子指出了我正确的位置,现在它正在工作,谢谢。
猜你喜欢
  • 2019-04-04
  • 2013-12-13
  • 1970-01-01
  • 2019-10-01
  • 1970-01-01
  • 2019-03-04
  • 1970-01-01
  • 2020-08-04
  • 2021-12-14
相关资源
最近更新 更多