php - 如何在 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”
解决方案
您需要一个定义 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();
推荐阅读
- hibernate - 在关系表中自动填充数据
- python - BeautifulSoup 在网络抓取亚马逊时无法正常工作
- c++ - 有没有办法从文本文件中读取并将单个数据存储为不同的变量?
- php - Symfony Container Builder 的 `addObjectResource` 方法
- java - 一段时间后无限亚军滞后
- rust - 如何在结构中写入 KdTree 成员的类型?
- flutter - 使用颤振关闭应用程序时,是否可以运行类似“后台服务”的代码?
- regex - Regex if then without else in ripgrep
- azure-logic-apps - 如何检查Outlook文件夹是否有邮件
- r - boxr 包中的 box_dir_create() 函数未在 Box 中创建文件夹