【发布时间】:2016-02-26 19:39:50
【问题描述】:
我试图在我的模型中增加一个完全独立于模型的自动递增 ID 的非自动递增整数列。
为了简化我要说的内容,考虑一张放书的桌子。在此表中,我们有四个字段:
Book_id (auto incrementing ID)
book_title (a string)
book_contents (Also a string for the purposes of this example)
book_edition (an integer representing the edition of the book. Think College textbooks)
假设我们有一本书叫“哈利波特”,另一本书叫“米老鼠”。我们的数据库目前看起来像这样
id: 1
book_title: "Harry Potter"
book_contents: "Book Contents"
book_edition: 1
--------------------------
id: 2
book_title: "Mickey Mouse"
book_contents: "This is a book about Mickey"
book_edition: 1
现在让我们说,出于某种原因,“哈利波特”这本书必须进行重大修改,无论是“导演剪辑版”还是其他类似的书,或者其他原因。该条目将如下所示
id: 3
book_title: "Harry Potter"
book_contents: "Updated book contents"
book_edition: 2
我的问题是在 Laravel 5+ 中获取原书版本的最佳方法是什么?
我是否需要实际执行 Model::where( {{ query to get latest }} ) 或者我可以用另一种方式处理这个问题吗?我看到有一个增量函数,但它没有很好地记录
作为第二个问题,如果我确实像上面提到的那样做了一个 Model::where,如果我将它包装在一个 Laravel DB::transaction 中,我是否可以免受可能的竞争条件,即两个人在同时? 示例
function saveBook()
{
DB::transaction(function ($arr) {
$latest = Book::where('book_title', '=', 'Harry Potter')->orderBy("book_edition", "desc")->first();
$this->book_edition = $latest->book_edition + 1;
$this->save();
});
}
这里有可能遇到竞态条件吗? 提前致谢!
【问题讨论】:
标签: php mysql laravel eloquent