【问题标题】:How can i get multiple table column name using Eloquent model如何使用 Eloquent 模型获取多个表列名
【发布时间】:2020-01-06 00:20:03
【问题描述】:

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

示例:我有两个表 1)User 2)Posts

1)User Iam 能够获取用户的所有列名称

class User extends Eloquent {

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

}

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

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    首先创建用户和帖子模态关系这样

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

    【讨论】:

      猜你喜欢
      • 2023-04-03
      • 2019-01-29
      • 2013-01-24
      • 2016-09-01
      • 2015-06-05
      • 2019-07-26
      • 2014-12-19
      • 1970-01-01
      • 2021-08-25
      相关资源
      最近更新 更多