【问题标题】:Get all fields from 'pivot' table从“数据透视”表中获取所有字段
【发布时间】:2018-05-17 12:52:05
【问题描述】:

有没有办法获取pivot表中的所有字段而不是一一指定?

例如(从指南here开始):

商店:

  • 身份证
  • 姓名

产品:

  • 身份证
  • 姓名

product_shop:

  • product_id
  • shop_id
  • field_1
  • field_2
  • field_3
  • ecc...

我不想指定每个字段:

public function products() {
   return $this->belongsToMany('App\Product')
        ->withPivot('field_1', 'field_2', 'field_3', 'ecc..' );
}

但我会返回表中所有可用的字段;类似->withPivot('*');

有办法吗?

谢谢。

【问题讨论】:

    标签: php eloquent pivot relationship laravel-5.6


    【解决方案1】:

    没有办法做到这一点,因为它会很复杂。

    为了防止冲突,Laravel 必须为枢轴列添加别名:

    `product_shop`.`field_1` as `pivot_field_1`, ...
    

    所以 Laravel 需要数据透视表中所有列的列表。获取此列表的唯一方法是单独查询information_schema.columns。

    【讨论】:

    • 这个答案对你有帮助吗?
    【解决方案2】:

    您可以通过首先从 product_shop 表中检索所有列(字段)并将其作为数组传递给 withPivot 来实现此目的。见以下代码:

    public function products() {
        $table_name = 'product_shop';
    
        // or you could get table name dynamically if you have a ProductShop model
        // $table_name = (new ProductShop)->getTable()
    
        $table_fields = Schema::getColumnListing($table_name);
    
        return $this->belongsToMany('App\Product')
        ->withPivot($table_fields);
    }
    

    别忘了导入 Schema:

    use Illuminate\Support\Facades\Schema; 
    

    我希望它对你有用。您可能希望按值从数组中删除一些字段。 This link explains how to remove some fields。

    【讨论】:

      猜你喜欢
      • 2016-11-21
      • 1970-01-01
      • 1970-01-01
      • 2022-07-21
      • 1970-01-01
      • 2016-11-09
      • 2011-09-07
      • 1970-01-01
      • 2014-01-08
      相关资源
      最近更新 更多