Laravel中Consignment模型如何按条件自动切换查询业务与归档数据表
实现方案
完全可以直接在Consignment Eloquent模型中重写对应查询方法实现该需求,无需修改外部调用Consignment::find(1)的代码。
具体实现代码
修改后的模型代码如下:
<?php namespace App\Models\Admin; use Illuminate\Database\Eloquent\Model; use Nicolaslopezj\Searchable\SearchableTrait; use Staudenmeir\EloquentHasManyDeep\HasRelationships; use Laravel\Scout\Searchable; class Consignment extends Model { // use SearchableTrait; use Searchable; use HasRelationships; protected $table = 'consignments'; // 定义归档表名常量,方便后续维护 const ARCHIVE_TABLE = 'archive_consignments'; // following function to search by id(laravel scout) public function getScoutKey() { return $this->id; } /** * 重写find方法,优先查主表,查不到查归档表 */ public static function find($id, $columns = ['*']) { // 先查主表 $result = parent::find($id, $columns); if ($result) { return $result; } // 主表查不到,临时切换到归档表查询 $instance = new static; $originalTable = $instance->getTable(); $instance->setTable(self::ARCHIVE_TABLE); $result = $instance->where($instance->getKeyName(), $id)->first($columns); // 切回原表,避免影响后续查询 $instance->setTable($originalTable); return $result; } /** * 如果需要支持findOrFail方法也可以同步重写 */ public static function findOrFail($id, $columns = ['*']) { $result = static::find($id, $columns); if ($result) { return $result; } throw new \Illuminate\Database\Eloquent\ModelNotFoundException; } }
注意事项
- 请确保
consignments和archive_consignments两张表的字段结构完全一致,否则查询出来的模型属性会出现缺失或异常 - 如果你需要对查询到的归档数据执行更新、删除操作,需要手动将模型的表临时切换为归档表,否则操作会作用到主表
- 如果需要覆盖
where()->first()这类非主键查询的场景,你可以选择重写newQuery方法合并两张表的查询,不过单主键查询场景下当前先查主表再查归档的方案性能最优 - 不要修改
$table属性的默认值,避免默认查询都走到归档表
内容的提问来源于stack exchange,提问作者web pakistan
相关产品推荐
相关产品推荐

