简体   繁体   中英

Laravel BelongsToMany Pivot Table : How to fetch selected columns

Want to get selected columns, when querying through pivot table. Following is my scenario. I have 3 tables,

  • coupons
  • coupon_cities
  • cities

relationship details are as following.

class Coupon extends Eloquent {

    public function cities(){

        return $this->belongsToMany('City', 'coupon_cities', 'coupon_id', 'city_id');
    }
}

When I query

Coupon::with('cities')

it returns array of all columns of city table for each entry of coupon row

The only way is this:

$coupon = Coupon->first();
$coupon->cities()->get([your columns here]);

Normally you'd do it like below:

Coupon::with(['cities' => function ($q)
{
  $q->select('column', 'column2' ...);
}

However it won't work for belongsToMany relation -> https://github.com/laravel/framework/pull/4440

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM