首页 > 解决方案 > 如何使用 Eloquent 模型获取多个表列名

问题描述

我在使用 eloquent 模型获取多个表列名称时遇到问题

示例:我有两个表 1)用户 2)帖子

1)用户我能够获取用户的所有列名

class User extends Eloquent {

    public function getTableColumns() {
        return $this->getConnection()->getSchemaBuilder()->getColumnListing($this->getTable());
    }

}

但我想要结合两个模型,即用户和帖子模式,并使用雄辩的模式获取所有列名

标签: phplaraveleloquent

解决方案


首先像这样创建用户和发布模式关系

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
       );
}

推荐阅读