Home > OS >  Why might the Elequent ORM relationship feel empty?
Why might the Elequent ORM relationship feel empty?

Time:01-17

Here is my method available in the controller

    public function getProductListAll(){
        $products = Product::with('property')
            ->whereStatus(1)
            ->where('show', 1)
            ->where('code', '!=', 1)
            ->where('is_roketable',true)
            ->with(['prices_roket' => function ($q) {
                return $q->whereNull('user_id');
            }]);
        $products = $products->whereIn('product_type', ['education', 'consultancy', 'startup']);

        $data['products']   = $products->select([
                'id', 'name', 'image', 'commission', 'price',
                'buy_now', 'type', 'short_desc', 'pricing_desc',
                'offer_status', 'period_status', 'period', 'period_frequency',
                'endpoint', 'product_type', 'unique_id', 'discount_show_status',
                'annual_payment', 'pre_register', 'privacy_status', 'privacy',
                'sg_project', 'last_pre_register_date', 'product_desc',
                'product_consulting', 'product_status',
            ])->get();

        return response()->json($data);


    }

and here is the relationship in my model.

 return $this->hasMany(ProductPrice::class)->select('price','created_at','user_id','offer_id')
            ->orderBy('price')
            ->where(function ($q) {
                $q
                    ->where(function ($q2) {
                        $q2->whereNull('offer_id');
                    })
                    ->orWhere(function ($q2) {
                        $q2->whereNotNull('offer_id');
                        $q2->where('user_id', auth()->user() ? auth()->user()->id : 0);
                    });
            });

I tried to change my relationship and rewrite it, but when I write select, I cannot access any data. When I remove select, they all come. I can't select at prices relationship.

CodePudding user response:

You can not use ->select() inside your model relationship.

Instead what you can do to limit the selection is by adding it into ->with()

For example

$products = Product::query()
   ->with(['property' => function ($q) {
       $q->select(['price','property.created_at','user_id','offer_id']);
   }])
   ->where( ... )
   // no need to add property 'price' inside this select
   ->select(['id', 'name', 'image', 'commission' ... ])
   ->get();
  • Related