如何在单行中搜索多个数据 mysql laravel

How to seach for multiple data in a single row mysql laravel

我想检查同一行中 3 列的值。我的专栏是

|column1|  column2 |column3 |
|-------|----------|--------|
| row1  |   row2   |  row3  |

我想检查第 1 行是否有值,如果没有,那么我想插入其中,与第 2 行相同,如果它没有我想插入的值,与第 3 行相同。目标是当用户注册时,我们会给他们 3 份礼物。所以当你注册row1,row2和row3为null时,我想在数据库中按照升序插入它们。

例如:如果第 1 行为空,则应将其从空更新为玩具或气球,然后更新为其他两行,但如果第二行有值,则应更新为第三行, 如果第三个有值那么它应该转到下一行

您使用行和列的方式有点混乱。

第一种情况,按照您提供的 table 和您的标题。您想要更新包含 3 列的单行。假设所述行也有一个像 id 这样的主键,你可以

$gift = Gift::find($id);
$gift->column1 = $row->column1 ? $row->column1 : $toy; //if empty, add toy
$gift->column2 = $row->column2 ? $row->column2 : $baloon; //if empty, add baloon
$gift->save();

第二种情况,您实际上正确地定义了它并将每个礼物放在不同的行中,并在礼物和用户之间创建了一对多的关系。在用户模型中:

public function gifts() {
    return $this->hasMany(Gift::class, 'user_id');
}

用户注册时,还没有赠送。您实际上毫不费力地一件一件地拿到了礼物。

$user = Auth::user();
$user->gifts()->saveMany([
    new Gift(['type' => 'toy', ...]); //fill all the attributes
    new Gift(['type' => 'toy', ...]); //fill all the attributes
    new Gift(['type' => 'toy', ...]); //fill all the attributes
]);

瞧!