首页 > 解决方案 > 如何在 laravel 模型中获取表属性

问题描述

我只想获取 wef 等于当前表 wef 的类型。如何实现这一点我无法使用 $this->attributes['wef'] 获取 wef 属性。提前致谢。

class Gst extends Model
    {
        //
        use Traits\UserAutoUpdate;
        protected $connection = 'mysql';
        protected $table = "gst";
        protected $fillable = ['name','wef'];

        public function types(){
           return $this->hasMany(GstType::class,'gst_id','id')->where('wef', $this->attributes['wef']);
        }   


    }

错误:“未定义的索引:wef”

标签: phplaravelmodel

解决方案


您需要一个定义 GstType 和 Gst 之间关系的函数:

public function gstTypes()
{
     return $builder->hasMany(GstType::class,'gst_id','id');
}

然后创建一个作用域函数:

public function scopeTypes($builder){
    return $builder->whereHas('gstTypes', function ($query) {
       $query->where('wef', $this->getAttribute('wef'));
   });
}   

并像这样使用它:

 $types = GstType::types();

推荐阅读