【问题标题】:how to get table Attribute inside laravel model如何在 laravel 模型中获取表属性
【发布时间】:2018-09-11 10:37:54
【问题描述】:

我只想获取 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"

【问题讨论】:

  • 我认为$this->attributes['wef'] 不会起作用。您需要在 types() 函数的参数中传递值。
  • 如果您正在使用急切加载.. 获取属性只是$this->wef
  • @Neha 工作正常吗?
  • 作为@DigitalDrifter 的回答.. 最好按照建议去做。

标签: php laravel model


【解决方案1】:

你需要一个定义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();

【讨论】:

  • 范围不会真正起作用。在大多数查询上下文中,您将没有任何可用的属性,您必须获取一个模型,然后在该模型上再次查询。这似乎不是正确的方法。
  • 对,但是属性“wef”应该来自哪里?
猜你喜欢
  • 2017-06-10
  • 2017-05-18
  • 2021-11-19
  • 2014-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-06
  • 2016-02-04
相关资源
最近更新 更多