Get specific columns having with() function in laravel

Category Model definition is:

class Category extends Model
    {
        public $implement = ['@RainLab.Translate.Behaviors.TranslatableModel'];
        public $translatable = ['name'];
    
        /**
         * @var string The database table used by the model.
         */
        public $table = 'shop_category';
    
        /**
         * @var array Validation rules
         */
        public $rules = [
        ];
        public $attachOne = [
          'icon' => 'System\Models\File'
        ];
    
          public $hasMany =[
            'shops' => ['ItScholarBd\Api\Models\Shop', 'key' => 'shop_category_id']
        ];
    }

I want to get category with shop. It works fine if I retrieve all columns but if I try to retrieve specific column it is not working. I want to get only the following columns: id, name of each table. I also apply a condition where Shop.status = 1. I am trying as follows:

   $this['categoryWithShop']  =   Category::select('id,name')->with(array('shops'=>function($query){
            $query->where('status','=',0);
            $query->select('id','name');
    }))->get();
    

Any idea?

2 answers

  • answered 2020-11-20 11:32 Maulik Shah

    Try this,

     $this['categoryWithShop']  =   Category::select('id,name')->with(array('shops'=>function($query){
            $query->where('status','=',0);
            $query->select('id','name', 'status');
    }))->get();
    

    In select query you need to pass that all columns which is needed in query.

  • answered 2020-11-20 12:05 Kamlesh Paul

    try this chaining method and select('id,name') this is wrong you need to fix this as select('id','name')

    ref link https://laravel.com/docs/8.x/queries#selects

    $this['categoryWithShop']  =   Category::select('id','name')->with(['shops' => function ($query) {
        $query->select('id', 'name')->where('status', '=', 0);
    }])->get();