簡體   English   中英

如何檢查 Laravel 中的雙向唯一記錄?

[英]How to check for two way unique record in Laravel?

我不確定這將如何工作,但我經常遇到這個問題。 如果只有一個主鍵,我可以使用它,但是有 2 個需要是唯一的。

我每次創建新記錄之前都必須檢查,是否沒有 Laravel 魔法可以用來在幕后檢查是否已經存在這樣的東西?

我不確定 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()
    ]);
}

我在我的User.php中有一個可能有幫助的關系?

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

取決於您想對結果做什么,因為我可以根據您希望更新用戶與特定課程的最后一次交互的列進行猜測,您可以像這樣實現:

$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