简体   繁体   English

如何检查 Laravel 中的双向唯一记录?

[英]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.如果只有一个主键,我可以使用它,但是有 2 个需要是唯一的。

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?我每次创建新记录之前都必须检查,是否没有 Laravel 魔法可以用来在幕后检查是否已经存在这样的东西?

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?我不确定 Laravel 是否提供双向主键,我真的不知道要在他们的文档中寻找什么,但想知道是否可以提供帮助?

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?我在我的User.php中有一个可能有帮助的关系?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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