【问题标题】:Laravel Eloquent : Get the value of related table instead of foriegn keyLaravel Eloquent:获取相关表的值而不是外键
【发布时间】:2018-08-31 07:18:14
【问题描述】:

我正在使用雄辩的查询

$apv = $node->products()->with('brand','skus.defaultImage')->get();

获取所有产品及其变体和其他相关模型。这是我得到的收藏:

在外部数组中的supplier_id 等位置 和outerarray>skus>values 数组中的option_id 我需要从(例如'sipplier_name')表列中获取相应的值,而不仅仅是外键。

【问题讨论】:

  • 您的product 模型是否有供应商关系?如果是这样,请将其添加到with 函数中

标签: php laravel eloquent


【解决方案1】:

谢谢大家。我在Model中添加了join语句

class Variant extends Model
{
    protected $guarded = ['id'];


    public function optval()
    {
        $intance = $this->hasMany(OptionValue::class);
         $intance->join('options', 'option_value.option_id', '=', 'options.id')            
            ->get(['option_label','value']);
     return $intance;
    }

}

【讨论】:

    【解决方案2】:
    class Product extends Model
    {
         ....
         ....
    
    
         public class supplier()
         {
              return $this->belongsTo('App\Supplier','supplier_id');
         }
    
    } 
    

    现在从供应商处获取产品

    $product = Product::where('id',$product_id)->with('supplier')->first();
    echo $supplier_name= $product->supplier['supplier_name'];
    

    【讨论】:

      【解决方案3】:

      你可以使用追加

      class Product extends Model
      {
           ....
           ....
      
           protected $appends = ['supplier_name'];
      
           public function supplier()
           {
                return $this->belongsTo(Supplier::class);
           }
      
           public function getSupplierNameAttribute()
           {
                 return $this->supplier()->supplier_name;
           }
      } 
      

      //示例使用

      $product = Product::first();
      $product->supplier_name;
      

      【讨论】:

      • public class ?是不是搞错了?
      • 哦..是的..这是一个错误..@SergeyShuryakov tq
      猜你喜欢
      • 2017-09-21
      • 2021-07-05
      • 1970-01-01
      • 1970-01-01
      • 2021-10-29
      • 2020-10-20
      • 2021-12-14
      • 2019-10-14
      • 1970-01-01
      相关资源
      最近更新 更多