【问题标题】:Get value from relationship key从关系键中获取值
【发布时间】:2020-08-11 22:42:10
【问题描述】:

我正在开发一个具有以下雄辩模型的 laravel 应用程序:

  • App\Models\Dumpdb - 这里存储所有文件信息;
  • App\Models\DumpDownloadHistory - 我在这里保存所有客户端文件的下载历史记录;

这是 Dumpdb 表和模型 -

// Database table
Schema::create('dumpdbs', function(Blueprint $table){
  $table->bigIncreaments('id');
  $table->string('hw')->nullable();
  $table->string('hwtype')->nullable();
  $table->string('hwtype2')->nullable();
  $table->integer('kw')->nullable();
  $table->string('dataset')->nullable();
  $table->string('enginetype')->nullable();
  $table->string('euro')->nullable();
  $table->timestamps();
});

// Model
<?php

namespace App\Models;

use App\Models\DumpDownloadHistory;
use Illuminate\Database\Eloquent\Model;

class Dumpdb extends Model
{
  public function DumpDownloadHistory(){
    return $this->hasMany(DumpDownloadHistory::class);
  }
}

DumpDownloadHistory 表和模型 -

// Table
Schema::create('dump_download_histories', function(Blueprint $table){
  $table->bigIncreaments('id');
  $table->unsignedBigInteger('user_id');
  $table->unsignedBigInteger('file_id');
  $table->string('dataset')->nullable();
  $table->integer('downloadCost')->nullable();
  $table->timestamps();

  $table->foreign('user_id')->references('id')->on('users');
  $table->foreign('file_id')->references('id')->on('dumpdbs');
});

// Model
<?php

namespace App\Models;

use App\Models\Dumpdb;

use Illuminate\Database\Eloquent\Model;

class DumpDownloadHistory extends Model
{
    protected $fillable = ['user_id', 'dataset', 'downloadCost', 'file_id'];

    protected $table = 'dump_download_histories';

    protected $primaryKey = 'id';

    public function dumpDb(){
      return $this->belongs_to(Dumpdb::class, 'file_id');
    }
}

我需要创建一个搜索过滤器,用户可以在其中搜索他已经拥有的文件 买。 例如,这是 Dumpdb 模型中的所有文件:

如果用户按下“已付款”复选框,这就是我想要的样子:

这是我得到的:

我的控制器:

    public function index(Request $request)
    {
      $dumpDb = Dumpdb::query();
      // Search values
      $hw = Dumpdb::select('hw')->distinct()->orderBy('hw', 'asc')->get();
      $pld = Dumpdb::select('hwtype')->distinct()->get();
      $hwtype = Dumpdb::select('hwtype', 'hwtype2')->distinct()->get();
      $kw = Dumpdb::select('kw')->whereNotNull('kw')->distinct()->orderBy('kw', 'asc')->get();
      $engine = Dumpdb::select('enginetype')->distinct()->get();
      $euro = Dumpdb::select('euro')->where('euro', '!=', 'NULL')->distinct()->get();

      // Search filters
      if ($request->has('hw') && $request->input('hw') != '') {
        $dumpDb = $dumpDb->where('hw', '=', $request->input('hw'));
      }

      if ($request->has('pld') && $request->input('pld') != '') {
        $dumpDb = $dumpDb->where(function ($query) use ($request) {
            $query->where('hwtype', $request->input('pld'))
                  ->orWhere('hwtype2', $request->input('pld'));
        });
      }

      if ($request->has('kw') && $request->input('kw') != '') {
        $dumpDb = $dumpDb->where('kw', '=', $request->input('kw'));
      }

      if ($request->has('engine') && $request->input('engine') != '') {
        $dumpDb = $dumpDb->where('enginetype', '=', $request->input('engine'));
      }

      if ($request->has('euro') && $request->input('euro') != '') {
        $dumpDb = $dumpDb->where('euro', '=', $request->input('euro'));
      }

      if ($request->has('ds') && $request->input('ds') != '') {
        $dumpDb = $dumpDb->where('dataset', 'LIKE', '%'. $request->input('ds') .'%');
      }

       // THIS FILTER NOT WORKING CORRECTLY
      if ($request->input('hasPayed') == '1') {
        $downloadHistory = DumpDownloadHistory::query();
        $dumpDb = $downloadHistory->where('user_id', auth()->user()->id)->where('downloadCost', '!=', 'NULL');
      }

      $dumpDb = $dumpDb->orderBy('id', 'desc')->paginate(30);
    return view('dumpDb.index', compact('hw', 'pld', 'kw', 'engine', 'euro', 'dumpDb',  'hwtype'));

任何帮助都会非常有用。提前致谢。

【问题讨论】:

    标签: php laravel search filter eloquent


    【解决方案1】:

    我认为您应该在获取 DumpDb 时包含关系。 Laravel 提供了多种方式来自动获取:

    Eager loading:

    $books = App\Book::with(['author', 'publisher'])->get();
    

    您应该从 DumpDb 查询 ($dumpDb-&gt;with('dumpDownloadHistory')) 中加载 DumpDownloadHistory。完成后,您可以更改过滤器以通过 constraining the eager loads 查询相关的 DumpDownloadHistory:

    $dumpDb = dumpDb->with(['dumpDownloadHistory' => function ($query) {
        $query->where('user_id', auth()->user()->id)->where('downloadCost', '!=', 'NULL');
    }]);
    

    如果 where 查询为真,这将简单地加载关系。但是,您还希望限制 DumpDb,因此您可以使用 whereHas

    $posts = App\Post::whereHas('comments', function (Builder $query) {
        $query->where('content', 'like', 'foo%');
    })->get();
    

    这只会加载具有某种类型关系的模型,因此您可以像这样使用它:

    $dumpDb = $dumpDb->whereHas('dumpDownloadHistory', function ($query) {
        $query->where('user_id', auth()->user()->id)->where('downloadCost', '!=', 'NULL');
    });
    

    更新


    编辑您的 DumpDb 模型以使用此关系:

    public function DumpDownloadHistory(){
        return $this->hasMany(DumpDownloadHistory::class, 'file_id');
    }
    

    您的最终控制器应如下所示:

    // THIS FILTER NOT WORKING CORRECTLY
    if ($request->input('hasPayed') == '1') {
        $dumpDb = $dumpDb->whereHas('dumpDownloadHistory', function ($query) {
            $query->where('user_id', auth()->user()->id)->where('downloadCost', '!=', 'NULL');
        });
    }
    

    摆脱$downloadHistory = DumpDownloadHistory::query();

    【讨论】:

    • 感谢您的回复。现在我收到错误:SQLSTATE[42S22]: Column not found: 1054 Unknown column 'dump_download_histories.dumpdb_id' in 'where clause' (SQL: select * from `dump_download_histories` where `dump_download_histories`.`dumpdb_id` in (2821, 2822, 2823, 2824, 2825, 2826, 2827, 2828, 2829, 2830, 2831, 2832, 2833, 2834, 2835, 2836, 2837, 2838, 2839, 2840, 2841, 2842, 2843, 2844, 2845, 2846, 2847, 2848, 2849, 2850) and `user_id` = 688 and `downloadCost` != NULL) 出于某种原因,我在关系上遇到错误。
    • 是的,没错,因为您只提供了它会自动查找 dumpdb_id 的关系,但如果我是对的,您正在使用 file_id。因此,您应该为关系提供“外键”。我已经更新了我的答案,以便为您提供正确的关系定义。
    • 非常感谢!现在可以了!我对关系感到困惑,如何在另一边建立联系,但现在我明白了。
    • 太棒了!祝你的项目好运。
    猜你喜欢
    • 1970-01-01
    • 2019-09-18
    • 2017-06-08
    • 1970-01-01
    • 2012-12-03
    • 2022-01-14
    • 2021-04-07
    • 1970-01-01
    • 2015-11-29
    相关资源
    最近更新 更多