是否有 insertUsing with ignore 选项?

Is there a insertUsing with ignore option?

在Laravel中,DB门面中存在两个有用的方法:

我需要结合这两种方法,即根据现有数据插入数据并忽略重复项。您知道在 Laravel 5.7 或更高版本中执行此操作的方法吗?

没有一种简单的方法可以做到这一点。但是可以用facade DB.

来实现

假设我们有 2 个模型:

class Car extends Model
{
    protected $table = "cars";

    protected $fillable = [
        "name",
        "production_year",
    ];
}
class Antique extends Model
{
    protected $table = "antiques";

    protected $fillable = [
        "name",
        "production_year",
        "category",
    ];
}

假设我们的任务是找到所有 1990 年之前制造的汽车,并根据它们制造类别为 'car' 的古董,忽略所有已经存在于 antiques[=26= 中的汽车] table.

这就是解决方案。

$selectQuery = Car::where('production_year', '<', 1990)->select([
    'name',
    'production_year',
    DB::raw('"car" as category'),
]);
$antiquesTable = (new Antique())->getTable();
$insertQuery = "INSERT IGNORE INTO $antiquesTable (
        `name`,
        `production_year`,
        `category`
    ) "
    . $selectQuery->toSql();
DB::insert($insertQuery, $selectQuery->getBindings());

它将生成以下 SQL 查询

INSERT IGNORE INTO antiques (`name`, `production_year`, `category`)
SELECT `name`, `production_year`, "car" AS category FROM cars WHERE `production_year` < 1990