如何使用Eloquent(Laravel)关系插入记录?

时间:2018-05-07 07:02:20

标签: php laravel eloquent

我有两个表:UserActivitiesActivities

活动:

| Column | Type             |
|--------|------------------|
| id     | int              |
| name   | varchar(255)     |
|        |                  |

UserActivities:

| Column      | Type | Comment                  |
|-------------|------|--------------------------|
| id          | int  |                          |
| user_id     | int  |                          |
| activity_id | int  | //id of activity by name |

现在将项目项目插入UserActivity模型我必须写两个这样的语句

$activity = Activity::where('name', '=', 'user_login')->first();
UserActivity::create(['user_id' => Auth::login(), 'activity_id' => $activity->id]);

虽然这很好,但我只是在阅读Eloquent relationships并想知道是否有办法创建belongsTo或某种关系并直接插入它

UserActivity::create(['user_id' => Auth::login(), 'activity' => 'user_login']);

它会通过搜索名称自动插入activity_id吗?有可能吗?

1 个答案:

答案 0 :(得分:0)

在阅读@kerbholz评论之后做了一些更多的研究后,我认为这是做到这一点的方法吗?

Activity.php(模型)

class Activity extends Model {
    public function user_activities() {
        return $this->hasMany(UserActivity::class);
    }
}

主要代码:

Activity::where('name', '=', 'user_login')->first()->user_activities()
    ->create(['user_id' => Auth::id()]);

或者在我的情况下,这确保活动名称始终存在:

Activity::updateOrCreate(['name' => 'user_test'])->user_activities()->create(['user_id' => 1]);