繁体   English   中英

Laravel Eloquent:获取相关表的值而不是前键

[英]Laravel Eloquent : Get the value of related table instead of foriegn key

我正在使用雄辩的查询

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

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

在这样的地方supplier_id外阵列和option_idouterarray>skus>values数组我需要从(如“对应的值sipplier_name ”)表列,而不只是一个外键。

您可以使用追加

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;
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'];

谢谢大家,我在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;
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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