【问题标题】:Laravel: dynamic property loading when not required in loopLaravel:循环中不需要动态属性加载
【发布时间】:2016-10-26 18:37:48
【问题描述】:

我有订阅表加入的客户模型和产品模型。当我运行类似的东西时 $customers = Customer::with(['products' => function($query) { $query->where('somecondition');}])->get();

如果我循环访问像这样的客户:

    foreach ($customers as $customer){
      foreach($customer->products as $product) {
        # do something
      }
    }

它通过使用动态属性加载客户的整个产品而忽略上述条件..如何解决这个问题?

我的课是

class Customer extends Model{

    public function products(){
        return $this->belongsToMany('App\Product', 'subscriptions')->withTimestamps()
    ->withPivot('qty', 'start_date', 'end_date');

    }
}

我在另一个函数中调用它:

           $customers = $request->user()->customers()->where('id', $request['customer_id'])->whereHas(
            'customerstatuses', function ($q) use ($p){
                $q->where('start_date', '<' ,$p)
                    ->where('end_date', '>' ,$p)
                    ->where('active_yn', '=' ,'1');
        })->with(['products'=>  function ($query) use ($p){
                $query->whereHas('productstatuses' ,function ($q) use ($p){
                $q->where('start_date', '<' ,$p)
                ->where('end_date', '>' ,$p)
                ->where('active_yn', '=' ,'1');
                })->wherePivot('start_date', '<', $p )
                    ->wherePivot('end_date', '>', $p)])->get();

【问题讨论】:

  • 你能显示真实的代码吗?

标签: laravel laravel-4 laravel-5 eloquent laravel-5.2


【解决方案1】:

你做错了..你应该这样做

$customers = Customer::with(['products' => function($query) { $query->where('somecondition');}]);

关系条件将在array

【讨论】:

  • 那是一个错字。但真正的问题是,当我不想要它时,它会在循环中调用动态属性
  • 哦,好吧。那很奇怪。您是否在$customers 上尝试过dd(),然后看看它返回了什么?请发布您的代码
  • 但是逻辑对吗? $customer 是 Customer 的一个实例,因此它使用动态属性加载产品
  • @qurius,请显示带有真实somecondition部分的真实代码。
  • @AlexeyMezenin 添加在上面
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-12
  • 2020-03-03
  • 1970-01-01
  • 2015-06-20
  • 1970-01-01
  • 2017-07-18
相关资源
最近更新 更多