php - 如何使用 Eloquent 模型获取多个表列名
问题描述
我在使用 eloquent 模型获取多个表列名称时遇到问题
示例:我有两个表 1)用户 2)帖子
1)用户我能够获取用户的所有列名
class User extends Eloquent {
public function getTableColumns() {
return $this->getConnection()->getSchemaBuilder()->getColumnListing($this->getTable());
}
}
但我想要结合两个模型,即用户和帖子模式,并使用雄辩的模式获取所有列名
解决方案
首先像这样创建用户和发布模式关系
在User.php模态类
public function post() {
return $this->hasMany(Post::class);
}
public function getTableColumns() {
return array_merge(
$this->getConnection()->getSchemaBuilder()->getColumnListing($this->getTable()), //user modal column
$this->post()->getTableColumns() //post modal column
);
}
Post.php模态类中的第二名
public function scopeGetTableColumns() {
return $this->getConnection()->getSchemaBuilder()->getColumnListing($this->getTable());
}
第三现在打开您的终端并运行:
php artisan tinker
(new \App\User)->getTableColumns();
您将使用关系获得两个表列..
否则,只需在User.php类函数中传递表名即可
public function getTableColumns($tableName = 'posts') {
return array_merge(
$this->getConnection()->getSchemaBuilder()->getColumnListing($this->getTable()), //user modal column
$this->getConnection()->getSchemaBuilder()->getColumnListing($tableName) //post modal column
);
}
推荐阅读
- java - 数组查找扫描器整数的索引
- python - 用来自另一个数据框的值填充多列
- dart - 是否可以在 Flutter Web 中为域添加前缀?
- python - 如何根据 Django 中的模型实例数填充 CreateView 字段
- python - 在 pandas 中应用函数的替代方法
- firebase - Flutter:在框架模块“firebase_core.FLTFirebasePlugin”中包含非模块化标头
- html - 按钮和视频在 HTML/Bootstrap 部分中不起作用
- binary-data - 量子计算与传统 base10 系统
- svelte - Svelte 有没有办法以非阻塞方式加载 {#each} 元素?
- android - 画中画 打开应用程序的新窗口并显示大量最近的任务