【问题标题】:Is there a insertUsing with ignore option?是否有带有忽略选项的 insertUsing ?
【发布时间】:2020-11-20 02:30:00
【问题描述】:

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

  • insertOrIgnore() - 在插入重复项时允许忽略操作
  • insertUsing() - 允许根据其他表中的数据插入数据

我需要结合这两种方法,即根据现有数据插入数据并忽略重复项。你知道在 Laravel 5.7 或更高版本中有什么方法吗?

【问题讨论】:

    标签: php laravel-5.7


    【解决方案1】:

    没有一种简单的方法可以做到这一点。但是可以通过门面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 年之前创建的所有汽车,并根据它们创建类别为“汽车”的古董,忽略 古董表中已经存在的所有汽车。

    这就是解决方案。

    $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
    

    【讨论】:

      猜你喜欢
      • 2010-10-27
      • 2013-01-30
      • 2015-02-18
      • 1970-01-01
      • 2013-06-08
      • 2014-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多