【问题标题】:Laravel relathionship with query builder get errorLaravel 与查询生成器的关系出错
【发布时间】:2021-02-13 12:16:04
【问题描述】:

我有 3 个与此表相关的表,我将调用此表

  1. belanja(父)
  2. anak_belanja(儿童)
  3. 供应商(与父母有关系)

我可以从父子关系创建此关系,但在表供应商上我得到一个错误。通常我使用“with”并且没有错误,但现在我使用查询生成器并且出现问题

我的 Belanja 模型

public function supplier()
{
    return $this->belongsTo(\App\Models\Suplier::class ,'supplier_id');
}

我的 Anak_Belanja 模型

public function belanja()
{
    return $this->belongsTo(\App\Models\Belanja::class ,'belanja_id');
}

这是我的控制器

public function render()
{
    $user_id = Auth::user()->id;
    $sub = SubRincianUraianKegiatan::where('user_id', $user_id)
    ->where('id' , $this->newid)
    ->pluck('uraian', 'id'); 
    $sup = Supplier::all()->pluck('nama' ,'id');
   
    $data = DB::table('belanja AS t')
    ->select([
    't.id',
    't.uraian',
    't.tgl_belanja',
    't.supplier_id',
    DB::raw('coalesce(sum(p.harga * p.qty),0) AS total_order')
    ])
    ->leftjoin('suplier AS s','t.suplier_id','=','s.id') // on here i think this error
    ->leftjoin('anak_belanja AS p','p.belanja_id','=','t.id')    
    ->where('sub_id', $this->newid)
    ->where('uraian', 'like', '%'.$this->search.'%')
    ->groupBy('t.id')
    ->groupBy('t.uraian')
    ->groupBy('t.tgl_belanja')
    ->groupBy('t.suplier_id')
    ->paginate(10);

    return view('livewire.detail-belanja-lw',
    ['data' => $data ,
    'sup' => $sup,
    'sub' => $sub,
    ]);
}

在我的刀片中,我尝试添加这样的供应商

 {{$i->supplier->nama}}

但我得到一个错误

未定义属性:stdClass::$supplier

谁能解释我的错误?

【问题讨论】:

  • 您不能在查询生成器对象中使用关系。关系只适用于雄辩。所以要么使用 eloquent,要么选择供应商名称并直接从查询构建器中使用。
  • 先生,我不知道该怎么做,我需要一些例子
  • 你想用eloquent还是想修改你当前的代码??
  • 我认为修改是最好的,因为我不需要更改我以前的查询,请先生帮助我
  • 然后在您的选择中也选择供应商名称。喜欢->select(['s.nama', ... ... ]) 并将其用作{{ $i->nama }}

标签: laravel eloquent query-builder


【解决方案1】:
$data = DB::table('belanja AS t')
->select([
't.id',
't.uraian',
't.tgl_belanja',
't.suplier_id',
DB::raw('coalesce(sum(p.harga * p.qty),0) AS total_order'),
DB::raw('s.nama as nama')
])
->leftjoin('suplier AS s','t.suplier_id','=','s.id') // on here i think this error
->leftjoin('anak_belanja AS p','p.belanja_id','=','t.id')    
->where('sub_id', $this->newid)
->where('uraian', 'like', '%'.$this->search.'%')
->groupBy('t.id')
->groupBy('t.uraian')
->groupBy('t.tgl_belanja')
->groupBy('t.suplier_id')
->paginate(10);

试试这个。

【讨论】:

  • nooooo,它不,它与这个查询无关,我需要在变量 $data 中解决
  • 你确定吗?因为 {{$i->suplier->nama}} suplier->nama 来自这个集合 $sup = Suplier::all()->pluck('nama' ,'id');
  • noo 。我将此 $sup 用于我的表单输入。我使用 livewire,所以我可以在我的渲染中添加它。它不是这样的。我在 $data 上的问题,它是有效的
  • 我对代码进行了更改,在选择中您必须添加 nama,例如,如果您有一个 foreach($data as $i) {{$i->nama} }
  • 您只需添加 DB::raw('s.nama as nama') 吗?但它仍然是错误
猜你喜欢
  • 2016-12-31
  • 2018-05-20
  • 2014-05-13
  • 2021-08-10
  • 1970-01-01
  • 1970-01-01
  • 2020-02-07
  • 1970-01-01
  • 2015-12-13
相关资源
最近更新 更多