jjzjj

php - GridView 中的 Yii2 列未显示(未设置)

coder 2024-04-18 原文

我正在尝试在我的 ActiveRecord Search() 中合并 3 个表。

我有这张 table

employees
id
first_name

projects
id
name

project_assignment
id
employee_id
project_id
date_added
date_removed

我正在使用 GridView 显示我数据库中的所有员工。 现在,我想显示分配员工的项目。所以说到这里,显然我们需要这 3 个表来连接。

在我的 Employees.php 模型中,我有这段代码:

public function getproject_assignment()
{
    return $this->hasMany(ProjectAssignment::className(), ['employee_id' => 'id']);
}

在我的 ProjectAssignment.php 模型中

/**
 * @return \yii\db\ActiveQuery
 */
public function getEmployee()
{
    return $this->hasOne(Employees::className(), ['id' => 'employee_id']);
}

/**
 * @return \yii\db\ActiveQuery
 */
public function getProject()
{
    return $this->hasOne(Projects::className(), ['id' => 'project_id']);
}

在我的 EmployeeSearch.php 中

class EmployeesSearch extends Employees
{
    public $project_name;
    public function rules()
    {
        return [
            [['id', 'employment_status_id'], 'integer'],
            [['project_name','string_id', 'first_name', 'last_name', 'middle_name', 'gender', 'birth_date', 'civil_status', 'phone', 'address', 'zip', 'email', 'position', 'start_date', 'tin', 'philhealth', 'sss', 'hdmf', 'photo_location'], 'safe'],
        ];
    }

   public function search($params)
    {

        $query = Employees::find();

        $query->addSelect(['projects.name as project_name','employees.*']);
        $query->leftJoin('project_assignment','project_assignment.employee_id = employees.id');
        $query->leftJoin('projects','projects.id = project_assignment.project_id');

        $query->andWhere([
            'project_assignment.date_removed' => NULL
        ]);


        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => array('pageSize' => 20),
        ]);


        $this->load($params);


        if (!$this->validate()) {
            // uncomment the following line if you do not want to any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
        ]);

        $query->andWhere([
            'employees.deleted_at' => NULL
            // 'projects.deleted_at' => NULL
        ]);

        $query->andFilterWhere(['like', 'string_id', $this->string_id])
            ->andFilterWhere(['like', 'first_name', $this->first_name])
            ->andFilterWhere(['like', 'last_name', $this->last_name])
            ->andFilterWhere(['like', 'middle_name', $this->middle_name])
            ->andFilterWhere(['like', 'gender', $this->gender])
            ->andFilterWhere(['like', 'civil_status', $this->civil_status])
            ->andFilterWhere(['like', 'phone', $this->phone])
            ->andFilterWhere(['like', 'address', $this->address])
            ->andFilterWhere(['like', 'zip', $this->zip])
            ->andFilterWhere(['like', 'email', $this->email])
            ->andFilterWhere(['like', 'position', $this->position])
            ->andFilterWhere(['like', 'tin', $this->tin])
            ->andFilterWhere(['like', 'philhealth', $this->philhealth])
            ->andFilterWhere(['like', 'sss', $this->sss])
            ->andFilterWhere(['like', 'hdmf', $this->hdmf])
            ->andFilterWhere(['like', 'photo_location', $this->photo_location]);

        return $dataProvider;
    } 

在我的index.php(查看文件)

$gridColumns = [
    [
        'attribute' => 'Project',
        'value' => 'projects', //the value means that this is the value of the column
                                                 //the zip here is the get parameter
        'filter' => Html::activeDropDownList($searchModel, 'project_name', ArrayHelper::map(\app\models\Projects::find()->asArray()->all(), 'id', 'name'),['class'=>'form-control','prompt' => 'Select Project']),
    ],
    'first_name',
    'middle_name',
    'last_name',
    // 'position',
    [
        'attribute' => 'position',
        'value' => 'position',
        'filter' => Html::activeDropDownList($searchModel, 'position', ArrayHelper::map(Employees::find()->groupBy('position')->asArray()->all(), 'position', 'position'),['class'=>'form-control','prompt' => 'Select Position']),
    ],
    ['class' => 'yii\grid\ActionColumn',
    'template' => '{update} {delete}'],

];

                <?php echo
                    GridView::widget([
                    'dataProvider' => $dataProvider,
                    'filterModel' => $searchModel,
                    'columns' => $gridColumns,
                        'export' => [
                            'fontAwesome' => true,
                        ]
                    ]);
                ?>

这里的问题是项目列没有显示任何内容。 这是一个截图:

当我检查 Yii Debuger 时,这个 sql 查询已经运行:

SELECT `projects`.`name` AS `project_name`, `employees`.* FROM `employees` LEFT JOIN `project_assignment` ON project_assignment.employee_id = employees.id LEFT JOIN `projects` ON projects.id = project_assignment.project_id WHERE (`project_assignment`.`date_removed` IS NULL) AND (`employees`.`deleted_at` IS NULL) LIMIT 20

这个查询是正确的,符合我的预期。唯一的问题是项目列没有显示为我上面显示的屏幕截图。

我不确定如何进行这项工作。已经抓挠我的头几个小时了。

请帮忙。谢谢你!

最佳答案

'value' => 'projects', //the value means that this is the value of the column

其实这里的value可以是string或者closure。如果它是一个字符串 那么它意味着一个表示要在该列中显示的属性名称的字符串documentation says .尝试使用闭包。在您的情况下,它将是这样的:

'value' => function ($model, $key, $index, $column){
    return $model->project->name;
}

关于php - GridView 中的 Yii2 列未显示(未设置),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30772270/

有关php - GridView 中的 Yii2 列未显示(未设置)的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  3. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  4. ruby-on-rails - Ruby net/ldap 模块中的内存泄漏 - 2

    作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代

  5. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  6. ruby-openid:执行发现时未设置@socket - 2

    我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass

  7. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  8. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  9. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

    我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

  10. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

随机推荐