【问题标题】:Laravel 5 collection issue: Where not equal toLaravel 5 集合问题:不等于
【发布时间】:2016-09-16 07:35:21
【问题描述】:

我目前正在开发一种用户可以插入 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 个小时。

~尼通J

【问题讨论】:

  • 而不是!= 尝试使用&lt;&gt;
  • 将 '!=' 替换为 '' 导致:prntscr.com/cili89
  • 这不是错$product_false = Product::all()-&gt;where('slug', '!=' , 'name')-&gt;get(); 吗?不应该是$product_false = Product::all()-&gt;where('slug', '!=' , $value-&gt;slug)-&gt;get();
  • 嘿,谢谢,但是,它不起作用。相反,我得到了:prntscr.com/cimdm8

标签: php laravel laravel-5.3 laravel-collection


【解决方案1】:

Collections、eloquent 和 query builder 是不一样的。 Collection 提供了一堆方法来处理数组,而不是数据库或模型。

在集合上下文中whereNot() 不可用。

但是同样的功能可以通过whereNotIn('key', [value])实现

collect([
    [
      'name' => 'foo',
      'rank' => 2
    ],[
      'name' => 'bar',
      'rank' => 3
    ],[
      'name' => 'foobar',
      'rank' => 4
    ],
 ])->whereNotIn('rank', [4])

where rank not in (4)

【讨论】:

    【解决方案2】:

    改变

    $product = Product::all()->where('slug', $value->slug)->first();
    $product_false = Product::all()->where('slug', '!=' , 'name')->get();
    

    进入

    $product = Product::where('slug', $value->slug)->first();
    $product_false = Product::where('slug', '!=' , 'name')->get();
    

    【讨论】:

    • 我以前试过。它是所有记录;包括 slug 和 name 实际上相等的那些:prntscr.com/cilj0n
    • 这可能是因为第三个参数被解析为字符串,尝试使用 products.slug 和 products.name 而不是只使用列名。您也可以使用,也许是更好的方法: $products_false = Product::whereRaw('slug != name');
    • product.slug / product.name 结果为:prntscr.com/cily1l ur whereRaw 建议结果为:prntscr.com/cilyjg 供以后参考,我只需要对产品型号进行测试并获取其中的记录“slug”列不等于“name”列。
    • 那是因为,当使用 whereRaw 时,您需要将 ->get() 附加到它,因为现在只返回查询生成器。
    【解决方案3】:

    试试这个

    $product = Product::where('slug', $value->slug)->first();
    $product_false = Product::whereRaw('slug != name')->get();
    

    简单的where 将不起作用,因为它将products.slug"name"(字符串)进行比较。

    【讨论】:

      【解决方案4】:

      我设法解决了它。

      $data = Excel::load($path, function($reader) {
      
                  $importedSlugs = $data->select(array('slug'))->toArray();
                          //collection of imported slugs
                          $collectionOfImportedSlugs = collect($importedSlugs)->flatten()->all();
      
                          //get all product slugs
                          $productSlugs = Product::all()->pluck('slug');
      
                          //get all different slugs!
                          $diffSlugsArray = $productSlugs->diff($collectionOfImportedSlugs)->all();
                          //dd($diffSlugsArray);
      
                          foreach ($diffSlugsArray as $diffSlug) {
                              $product_false = Product::all()->where('slug',     $diffSlug)->first();
      
                              echo $product_false->slug . 'has been deleted!';
      
                              $product_false->delete();
                          }
              })->get();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-06
        • 2016-04-24
        • 2015-05-29
        • 2016-12-21
        • 2018-06-19
        • 2015-12-31
        相关资源
        最近更新 更多