我目前正在开发一种用户可以插入 excel 文件的模式。如果记录是新的或与数据库中存在的记录相同,则系统的任务是上传和/或添加新的数据库记录。但它还需要一个删除函数来删除那些 slug 列与 name 列不同的记录。
目前我正在使用Laravel 5.3,这是我现在的控制器:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Product;
use App\Http\Requests;
use Illuminate\Support\Facades\DB;
use Input;
use Maatwebsite\Excel\Facades\Excel;
class ProductsController extends Controller {
public function importExcel(Request $request) {
if (Input::hasFile('productFile')) {
$path = Input::file('productFile')->getRealPath();
$checkbox = Input::get('productCheckbox');
$data = Excel::load($path, function($reader) {
})->get();
if (!empty($data) && $data->count()) {
foreach ($data as $key => $value) {
$product = Product::all()->where('slug', $value->slug)->first();
$product_false = Product::all()->where('slug', '!=' , 'name')->get();
if ($product_false !== null){
//delete row if slug does not matches name
dd($product_false);
}
上面的 dd 返回所有产品,因此集合查询无法正常工作(有关我尝试在此集合中运行的原始 SQL,请参见下文)
if ($product !== null) {
//update row if exist
$product->name = $value->name;
$product->description = $value->description;
$product->price = $value->price;
$product->save();
} else {
//add new row if not exist
$product = new Product;
$product->slug = $value->slug;
$product->name = $value->name;
$product->description = $value->description;
$product->price = $value->price;
$product->save();
}
}
header("Location: /products");
}
}
}
}
这是产品型号:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'slug', 'name', 'description', 'price',
];
}
这是我基本上要在集合中使用的 PHPMyAdmin 原始 SQL(有效):
SELECT * FROM `products` WHERE `slug` != `name`
我希望有人能帮助我摆脱这个坑。为了完成这件事,我已经在互联网的浪潮中航行了大约 12 个小时。
~ nitsuJ