简体   繁体   中英

How to check for two way unique record in Laravel?

I'm not sure how this would work, but I run into this issue a lot. If there was just one primary key, I could work with that, but theres 2 that need to be unique.

I have to check every time before I create anew record, is there no Laravel magic that I can use to check behind the scenes if something like this exists already?

I'm not sure if a two way primary key is something Laravel offers, I don't really know what to be looking for in their documentation but was wondering if one could help?

if (CourseEntry::where('course_id', $course->id)->where('user_id', Auth::user()->id)->count() < 1) {
    CourseEntry::create([
        'course_id' => $course->id,
        'user_id' => Auth::user()->id,
        'last_interaction' => Carbon::now(),
        'started_at' => Carbon::now()
    ]);
}

I have a relationship in my User.php that could maybe help?

public function courseEntries() {
    return $this->hasMany('App\Models\CourseEntry');
}

Depends on what you want to do with the result, as I can guess based on the columns that you would like to update the last interaction of the user with a particular course you can achieve that like this:

$courseEntry = CourseEntry::firstOrNew([ 
        'course_id' => $course->id,
        'user_id' => Auth::user()->id 
    ],
    [
        'started_at' => Carbon::now() // this should be set just the first time, when the user entry does not exists
    ]);

$courseEntry->last_interaction = Carbon::now(); // this should be updated each time.
$courseEntry->save();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM