List only the records created by the logged in user

I have two tables,
tblObra
and
tblUser
There is a relationship through the user.id field and obra.created_by.
He intended that only the records in the index.php, of the user logged on the basis of the said list, be listed.
Thank you.

In list query add $query->where(['created_by' => Yii::$app->user->id]); for logged in user

Thank you very much …
But I have another challenge … this listing only for users with the ‘member’ rule,
the next code gives an error … what could be wrong.

public function search($params)
{
$query = Obra::find()->alias(‘im’);

	// add conditions that should always apply here
	$query->joinWith(['imovel', 'imovelfraccao', 'distrito', 'origempedido', 'requerente']);

	if (Yii::$app->user->can('member')) {
		// ...
    $query = Obra::find()->where(['created_by' => Yii::$app->user->id])->alias('im');
	
	$query->joinWith(['imovel', 'imovelfraccao', 'distrito', 'origempedido', 'requerente']);		
	}

	if (Yii::$app->user->can('premium')) {
		// ...
    $query = Obra::find()->alias('im');
	
	$query->joinWith(['imovel', 'imovelfraccao', 'distrito', 'origempedido', 'requerente']);
	}

(…).

What error do you get?

Seems like you are using a table alias, which can cause two errors from looking at your code:

  1. In ->where([‘created_by’ => Yii::$app->user->id]) argument, you are not using the table alias. The correct way to work in your case is to write it like this:

->where([‘im.created_by’ => Yii::$app->user->id])

  1. Check for the use of your table alias on the functions that links the model “Obra” to the others, like “imovel” and “imovelfraccao”.

Other error might be happening, be can find with only this code.

I haven’t had a chance to test Bruno Pannata’s tip yet but maybe it could work.
Still, and for the sake of example, I leave the code here. So, in modelSearch I have the following code …


public function search($params)
{
$query = Obra::find()->alias(‘im’);

	// add conditions that should always apply here
	$query->joinWith(['imovel', 'imovelfraccao', 'distrito', 'origempedido', 'requerente']);	   

	if (Yii::$app->user->can('member')) {
	// ...
		$query = Obra::find()->where(['created_by' => Yii::$app->user->id])->alias('im');
	}

	if (Yii::$app->user->can('employee')) {
	// ...
    $query = Obra::find()->alias('im');

	$query->joinWith(['imovel', 'imovelfraccao', 'distrito', 'origempedido', 'requerente']);
	}
	
	if (Yii::$app->user->can('premium')) {
	// ...
    $query = Obra::find()->alias('im');

	$query->joinWith(['imovel', 'imovelfraccao', 'distrito', 'origempedido', 'requerente']);
	}		

	if (Yii::$app->user->can('admin')) {
	// ...
    $query = Obra::find()->alias('im');

	$query->joinWith(['imovel', 'imovelfraccao', 'distrito', 'origempedido', 'requerente']);
	}

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
        'sort'=> [
            'defaultOrder' => [
                'id' => SORT_DESC
				]
            ],
        'pagination' => [
            'pageSize' => 100],   // fsilva
    ]);

	// add conditions that should always apply here
	//$query->joinWith(['imovel', 'imovelfraccao']);  // fsilva  
	//$query->joinWith(['imovelfraccao']);  // fsilva

    $this->load($params);

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

    // grid filtering conditions
    $query->andFilterWhere([
		//self::obra() . 'im.id' => $this->id,
        'im.id' => $this->id,
        'ano_id' => $this->ano_id,
        'mes_id' => $this->mes_id,
        //'imovel_id' => $this->imovel_id,
        //'imovelfraccao_id' => $this->imovelfraccao_id,
        'distrito_obra' => $this->distrito_obra,
        'inquilino_id' => $this->inquilino_id,
		//'origempedido_id' => $this->origempedido_id,
        //'requerente_id' => $this->requerente_id,
        'data_aval' => $this->data_aval,
        'fornecedor_id' => $this->fornecedor_id,
        'custo_obra' => $this->custo_obra,
        'custo_obratotal' => $this->custo_obratotal,
        'data_registo' => $this->data_registo,
        'data_pedido' => $this->data_pedido,
        'data_autorizacao_obra' => $this->data_autorizacao_obra,
        'data_adjudicacao' => $this->data_adjudicacao,
        'data_inicio_obra' => $this->data_inicio_obra,
        'data_fim_obra' => $this->data_fim_obra,
        'cod_status' => $this->cod_status,
        'cod_control' => $this->cod_control,
		'numdocs' => $this->numdocs,
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,
        'created_by' => $this->created_by,
        'updated_by' => $this->updated_by,
    ]);

    $query->andFilterWhere(['like', 'ano', $this->ano])
        ->andFilterWhere(['like', 'entidade_sigla', $this->entidade_sigla])
		->andFilterWhere(['like', 'distrito_obra_ext', $this->distrito_obra_ext])
        ->andFilterWhere(['like', 'sla', $this->sla])
        ->andFilterWhere(['like', 'npd', $this->npd])
        ->andFilterWhere(['like', 'cabimento', $this->cabimento])
        ->andFilterWhere(['like', 'compromisso', $this->compromisso])
        ->andFilterWhere(['like', 'patologia_avaliacao', $this->patologia_avaliacao])
        ->andFilterWhere(['like', 'responsavel_aval', $this->responsavel_aval])
        ->andFilterWhere(['like', 'origem_pedido', $this->origem_pedido])
		->andFilterWhere(['like', 'entidade_tratamento', $this->entidade_tratamento])
        ->andFilterWhere(['like', 'patologia_obra', $this->patologia_obra])
        ->andFilterWhere(['like', 'tipo_aquisicao', $this->tipo_aquisicao])
        ->andFilterWhere(['like', 'requesitado_por', $this->requesitado_por])
        ->andFilterWhere(['like', 'obs', $this->obs])
        ->andFilterWhere(['like', 'notas', $this->notas])
        ->andFilterWhere(['like', 'responsavel_autorizacao', $this->responsavel_autorizacao])
        ->andFilterWhere(['like', 'parecer', $this->parecer])
        ->andFilterWhere(['like', 'update_file_um', $this->update_file_um])
        ->andFilterWhere(['like', 'update_file_dois', $this->update_file_dois])
        ->andFilterWhere(['like', 'update_file_tres', $this->update_file_tres])
        ->andFilterWhere(['like', 'update_file_quatro', $this->update_file_quatro])
        ->andFilterWhere(['like', 'update_file_cinco', $this->update_file_cinco])
        ->andFilterWhere(['like', 'estado_obra', $this->estado_obra])
        ->andFilterWhere(['like', 'status_pedido', $this->status_pedido])
		->andFilterWhere(['like', 'imovel.descritivo_imovel', $this->imovel_id])
		//->andFilterWhere(['like', 'imovel.num_predio', $this->imovel_id])
		->andFilterWhere(['like', 'imovelfraccao.num_fraccao', $this->imovelfraccao_id])
		->andFilterWhere(['like', 'imovel.entidade', $this->entidade])
		->andFilterWhere(['like', 'origempedido.descricao', $this->origempedido_id])
		->andFilterWhere(['like', 'requerente.nome_requerente', $this->requerente_id])			
		->andFilterWhere(['like', 'distrito.nome_distrito', $this->distrito_obras]);
    return $dataProvider;

In index.php I have the following code …

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
	//'layout'=>"\n{pager}\n{summary}\n{items}",
	//'emptyCell' => '---',
	// parameters from the demo form
	//'bordered' => true,
	//'striped' => true,
	// Crie um layout de painel para o widget GridView	
	//'showPageSummary' => true,
	'headerRowOptions' => ['class' => 'kartik-sheet-style'],
	'filterRowOptions' => ['class' => 'kartik-sheet-style'],		
	'pjax' => true,
	'condensed' => true,
	'responsive' => true,
	'hover' => true,
	// Cabeçalho flutuante fixo na parte superior e um deslocamento de 50 px na parte superior da página da barra de navegação de autoinicialização	
	'floatHeader' => true,
	//'floatHeaderOptions' => ['top' => '50'],
	// Redimensionar as colunas		
	//'hideResizeMobile' => true,								 
	'resizableColumns' => true,
	'persistResize' => false,		
	'panel' => [
		'heading'=>'<h3 class="panel-title"><i class="glyphicon glyphicon-eye-open"></i> Tabela - Listagem de Aquisições/Obras</h3>',
		'type'=>'primary',
		//'after'=>Html::a('<i class="glyphicon glyphicon-plus"></i> Create Country', ['create'], ['class' => 'btn btn-success']),
		'before'=>Html::a('<i class="fas fa-redo"></i> Limpar pesquisa', ['index'], ['class' => 'btn btn-info btn-sm']),
		//'footer' => false,
	],
	//'panel' => ['type' => 'primary', 'heading' => 'Tabela - Listagem de Obras'],																			
	//'toggleDataContainer' => ['class' => 'btn-group mr-2'],
	'rowOptions' => function ($model) {
		if ($model->status_pedido == 'Cancelado') {
        return ['class' => 'danger'];  // 'class' => 'danger' / 'class' => 'success' - 'warning' - 'info'
		}
		else if ($model->patologia_avaliacao == 'Sim') {
			return ['class' => 'success'];
		}
	},

	// set export properties
	'export'=>[
		'fontAwesome' => false,
		'showConfirmAlert' => false,
		'target' => GridView::TARGET_BLANK
	],

	'exportConfig' => [
		GridView::EXCEL =>  [
            'label'           => 'Formato Excel',
            //'icon'            => 'file-excel-o',
            //'iconOptions'     => ['class' => 'text-success'],
            'showHeader'      => TRUE,
            'showPageSummary' => TRUE,
            'showFooter'      => TRUE,
            'showCaption'     => TRUE,
            //'filename'        => $exportFilename,
            'alertMsg'        => 'The EXCEL export file will be generated for download.',
            'options'         => ['title' => 'Microsoft Excel 95+'],
            'mime'            => 'application/vnd.ms-excel',
            'config'          => [
                'worksheet' => 'Listagem_Obras',
                'cssFile'   => '',
            ],
        ],
		GridView::CSV => [
			'label' => 'Formato CSV',
			//'icon'            => 'file-code-o',
			//'iconOptions'     => ['class' => 'text-primary'],
			'showHeader'      => TRUE,
			'showPageSummary' => TRUE,
			'showFooter'      => TRUE,
			'showCaption'     => TRUE,
			//'filename'        => $exportFilename,
			'alertMsg'        => 'O ficheiro de exportação CSV será gerado para download.',
			'options'         => ['title' => 'Comma Separated Values'],
			'mime'            => 'application/csv',
			'config'          => [
				'colDelimiter' => ",",
				'rowDelimiter' => "\r\n",
			]	
		],
		GridView::PDF => [
			'label' => 'Formato PDF',
			//'icon'            => 'file-pdf-o',
            //'iconOptions'     => ['class' => 'text-danger'],
            'showHeader'      => TRUE,
            'showPageSummary' => TRUE,
            //'showFooter'      => TRUE,
            'showCaption'     => TRUE,
            //'filename'        => 'SSPSP-Obras',
            'alertMsg'        => 'O ficheiro de exportação PDF será gerado para download.',
            'options'         => ['title' => 'PDF - Portable Document Format'],
            'mime'            => 'application/pdf',
            'config'          => [
                'mode'          => 'c',
                'format'        => 'A4-L',
                'destination'   => 'D',
                'marginTop'     => 20,
                'marginBottom'  => 20,
                'cssInline'     => '.kv-wrap{padding:20px;}' .
                    '.kv-align-center{text-align:center;}' .
                    '.kv-align-left{text-align:left;}' .
                    '.kv-align-right{text-align:right;}' .
                    '.kv-align-top{vertical-align:top!important;}' .
                    '.kv-align-bottom{vertical-align:bottom!important;}' .
                    '.kv-align-middle{vertical-align:middle!important;}' .
                    '.kv-page-summary{border-top:4px double #ddd;font-weight: bold;}' .
                    '.kv-table-footer{border-top:4px double #ddd;font-weight: bold;}' .
                    '.kv-table-caption{font-size:1.5em;padding:8px;border:1px solid #ddd;border-bottom:none;}',
				'methods'       => [
					//'SetHeader' => [
					//['odd' => $ourPdfHeader, 'even' => $ourPdfHeader]
					//],
					//'SetFooter' => [
						//['odd' => $ourPdfFooter, 'even' => $ourPdfFooter]
					//],
				],
				'options'       => [
					'title'    => 'Custom Title',
					'subject'  => 'PDF export',
					'keywords' => 'pdf'
				],
				'contentBefore' => '',
				'contentAfter'  => ''
            ]
		],
		GridView::HTML => [
			'label' => 'Formato Html',
            //'icon'            => 'file-text',
            //'iconOptions'     => ['class' => 'text-info'],
            'showHeader'      => TRUE,
            'showPageSummary' => TRUE,
            'showFooter'      => TRUE,
            'showCaption'     => TRUE,
            //'filename'        => $exportFilename,
            'alertMsg'        => 'O ficheiro de exportação HTML será gerado para download.',
            'options'         => ['title' => 'Hyper Text Markup Language'],
            'mime'            => 'text/html',
            //'config'          => [
            //'cssFile' => 'http://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css'
			//],
		],	
		GridView::TEXT => [ 'label' => 'Formato Text'],
	],

	'pager' => [
		'firstPageLabel' => 'Primeiro registo',
		'lastPageLabel' => 'Último registo',
		'maxButtonCount' => 7,    // Set maximum number of page buttons that can be displayed
		'options' => [
			'class' => 'pagination pagination-sm'
		],
	],

    'columns' => [
        //['class' => 'yii\grid\SerialColumn'],
        //'id',
		[
		'attribute' => 'id',
        'label' => 'ID. Obra',
        'format' => 'raw',
		'vAlign'=>'middle',			
		'options' => ['width' => '64'],    // fsilva
        //'headerOptions' => ['width' => '160'],  // fsilva  			
		],
        //'ano_id',
        //'ano',
        [                       /* fsilva  DropdownList p/ pesquisa  */
        'attribute'=>'ano',
        'label'=> 'Ano',
		'vAlign'=>'middle',
		//'options' => ['width' => '48'],    // fsilva			
        'filter'=>ArrayHelper::map(\app\models\Obra::find()->orderBy('ano')->asArray()->all(), 'ano', 'ano'),
        ],
        //'mes_id',			
        //[                       /* fsilva  DropdownList p/ pesquisa  */
        //'attribute'=>'mes_id',
        //'label'=> 'Mês',            
        //'filter'=>ArrayHelper::map(\app\models\Mes::find()->orderBy('id')->asArray()->all(), 'id', 'mesL'), 
        //],			
        //'imovel_id',
		//'imovel.descritivo_imovel',   //  fsilva  Relação entre as tabelas
		//[
        //'attribute' => 'imovel.descritivo_imovel',   //  fsilva  Relação entre a tabela imovel e obra
        //'label' => 'Imovel',
        //'value' => 'imovel.descritivo_imovel'
        //],
        //'data_pedido',
        [
        'attribute' => 'data_pedido',
		'label'=> 'Data do Pedido',			
        'value' => 'data_pedido',
        'format' => 'date',
		'vAlign'=>'middle',
		//'options' => ['width' => '200'],    // fsilva
        //'headerOptions' => ['width' => '160'],  // fsilva  
        'filter' => DatePicker::widget([
            'model' => $searchModel,
            'attribute' => 'data_pedido',
            'language' => 'pt',
            'clientOptions' => [
                'autoClose' => TRUE,
                'format' => 'yyyy-mm-dd',
                ]
            ]),
        ],							
        // 'npd',
		// [
		// 'attribute' => 'npd',			
        // 'label' => 'NPD',
        // 'format' => 'raw',
		// 'vAlign'=>'middle',
		// ],
		//'entidade_sigla',
		// [
		// 'attribute' => 'entidade',            
		// 'label' => 'Entidade',
        // 'format' => 'raw',
		// 'vAlign'=>'middle',
		// 'options' => ['width' => '97'],    // fsilva
        //'headerOptions' => ['width' => '160'],  // fsilva
		// //'filter'=>ArrayHelper::map(\app\models\Imovel::find()->orderBy('entidade')->asArray()->all(), 'entidade', 'entidade'),
		// 'value' => 'imovel.entidade',
		// ],
		//[
		//'attribute' => 'entidade_sigla',
		//'label' => 'Entidade',
		//'format' => 'raw',
		//'vAlign'=>'middle',
		//'filter'=>ArrayHelper::map(\app\models\Obra::find()->orderBy('entidade_sigla')->asArray()->all(), 'entidade_sigla', 'entidade_sigla'),
		//],
		[
		'attribute' => 'distrito_obras',            
		'label' => 'Distrito',
        'format' => 'raw',
		'vAlign'=>'middle',
		'options' => ['width' => '97'],    // fsilva
        //'headerOptions' => ['width' => '160'],  // fsilva
		'filter'=>ArrayHelper::map(\app\models\Distrito::find()->orderBy('id')->asArray()->all(), 'nome_distrito', 'nome_distrito'),
		'value' => 'imovel.distrito.nome_distrito',
		],
		//[
		//'attribute' => 'distrito_obra_ext',
		//'label' => 'Distrito',
		//'format' => 'raw',
		//'vAlign'=>'middle',
		//'filter'=>ArrayHelper::map(\app\models\Obra::find()->orderBy('distrito_obra_ext')->asArray()->all(), 'distrito_obra_ext', //'distrito_obra_ext'),
		//],
		//'distrito_obra',
		[
		'attribute' => 'imovel_id',            
		'label' => 'Morada do Imóvel',
        'format' => 'raw',
		'vAlign'=>'middle',
        'value' => function ($data) {
			return Html::a($data->imovel->descritivo_imovel, ['/imovel/view', 'id' => $data->imovel_id]);
            },
		],
		//'imovelfraccao_id',	
		//'imovelfraccao.num_fraccao',			
		//[
		//'attribute' => 'num_inquilino',			
        //'label' => 'Numero Fracção',
        //'format' => 'raw',
        //'value' => function ($data) {
		//	return Html::a($data->imovelfraccao->num_inquilino,);  // ['/imovelfraccao/view', 'id' => $data->imovel_id]);
        //    },
		//],
		[
		'attribute' => 'imovelfraccao_id',			
        'label' => 'Fracção no Imóvel',
        'format' => 'raw',
		'vAlign'=>'middle',
        'value' => function ($data) {
			return Html::a($data->imovelfraccao->num_fraccao, ['/imovelfraccao/view', 'id' => $data->imovel_id]);
            },
		],

When I do a search for the district or Residence field of the property or Fraction of the property it gives the following error…

Database Exception – yii\db\Exception

SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘distrito.nome_distrito’ in ‘where clause’

The SQL being executed was: SELECT COUNT(*) FROM obra im WHERE (created_by=2) AND (distrito.nome_distrito LIKE ‘%Lisboa%’)

Error Info: Array ( [0] => 42S22 [1] => 1054 [2] => Unknown column ‘distrito.nome_distrito’ in ‘where clause’ )

Caused by: PDOException

SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘distrito.nome_distrito’ in ‘where clause’

in C:\xampp\htdocs\sspspPGOA_protected\vendor\yiisoft\yii2\db\Command.php at line 1299

When I remove the possibility of searching those fields, the application responds. The problem is in the way the query ‘assembles’ the relations between tables.

Grateful for your availability.

Sorry but the modelSearch code I put in does not appear in the best form … I leave here the most complete code…

public function search($params)
{
$query = Obra::find()->alias(‘im’);

	// add conditions that should always apply here
	$query->joinWith(['imovel', 'imovelfraccao', 'distrito', 'origempedido', 'requerente']);	   

	if (Yii::$app->user->can('member')) {
	// ...
		$query = Obra::find()->where(['created_by' => Yii::$app->user->id])->alias('im');
	}

	if (Yii::$app->user->can('employee')) {
	// ...
    $query = Obra::find()->alias('im');

	$query->joinWith(['imovel', 'imovelfraccao', 'distrito', 'origempedido', 'requerente']);
	}
	
	if (Yii::$app->user->can('premium')) {
	// ...
    $query = Obra::find()->alias('im');

	$query->joinWith(['imovel', 'imovelfraccao', 'distrito', 'origempedido', 'requerente']);
	}		

	if (Yii::$app->user->can('admin')) {
	// ...
    $query = Obra::find()->alias('im');

	$query->joinWith(['imovel', 'imovelfraccao', 'distrito', 'origempedido', 'requerente']);
	}

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
        'sort'=> [
            'defaultOrder' => [
                'id' => SORT_DESC
				]
            ],
        'pagination' => [
            'pageSize' => 100],   // fsilva
    ]);

	// add conditions that should always apply here
	//$query->joinWith(['imovel', 'imovelfraccao']);  // fsilva  
	//$query->joinWith(['imovelfraccao']);  // fsilva

    $this->load($params);

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

    // grid filtering conditions
    $query->andFilterWhere([
		//self::obra() . 'im.id' => $this->id,
        'im.id' => $this->id,
        'ano_id' => $this->ano_id,
        'mes_id' => $this->mes_id,
        //'imovel_id' => $this->imovel_id,
        //'imovelfraccao_id' => $this->imovelfraccao_id,
        'distrito_obra' => $this->distrito_obra,
        'inquilino_id' => $this->inquilino_id,
		//'origempedido_id' => $this->origempedido_id,
        //'requerente_id' => $this->requerente_id,
        'data_aval' => $this->data_aval,
        'fornecedor_id' => $this->fornecedor_id,
        'custo_obra' => $this->custo_obra,
        'custo_obratotal' => $this->custo_obratotal,
        'data_registo' => $this->data_registo,
        'data_pedido' => $this->data_pedido,
        'data_autorizacao_obra' => $this->data_autorizacao_obra,
        'data_adjudicacao' => $this->data_adjudicacao,
        'data_inicio_obra' => $this->data_inicio_obra,
        'data_fim_obra' => $this->data_fim_obra,
        'cod_status' => $this->cod_status,
        'cod_control' => $this->cod_control,
		'numdocs' => $this->numdocs,
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,
        'created_by' => $this->created_by,
        'updated_by' => $this->updated_by,
    ]);

    $query->andFilterWhere(['like', 'ano', $this->ano])
        ->andFilterWhere(['like', 'entidade_sigla', $this->entidade_sigla])
		->andFilterWhere(['like', 'distrito_obra_ext', $this->distrito_obra_ext])
        ->andFilterWhere(['like', 'sla', $this->sla])
        ->andFilterWhere(['like', 'npd', $this->npd])
        ->andFilterWhere(['like', 'cabimento', $this->cabimento])
        ->andFilterWhere(['like', 'compromisso', $this->compromisso])
        ->andFilterWhere(['like', 'patologia_avaliacao', $this->patologia_avaliacao])
        ->andFilterWhere(['like', 'responsavel_aval', $this->responsavel_aval])
        ->andFilterWhere(['like', 'origem_pedido', $this->origem_pedido])
		->andFilterWhere(['like', 'entidade_tratamento', $this->entidade_tratamento])
        ->andFilterWhere(['like', 'patologia_obra', $this->patologia_obra])
        ->andFilterWhere(['like', 'tipo_aquisicao', $this->tipo_aquisicao])
        ->andFilterWhere(['like', 'requesitado_por', $this->requesitado_por])
        ->andFilterWhere(['like', 'obs', $this->obs])
        ->andFilterWhere(['like', 'notas', $this->notas])
        ->andFilterWhere(['like', 'responsavel_autorizacao', $this->responsavel_autorizacao])
        ->andFilterWhere(['like', 'parecer', $this->parecer])
        ->andFilterWhere(['like', 'update_file_um', $this->update_file_um])
        ->andFilterWhere(['like', 'update_file_dois', $this->update_file_dois])
        ->andFilterWhere(['like', 'update_file_tres', $this->update_file_tres])
        ->andFilterWhere(['like', 'update_file_quatro', $this->update_file_quatro])
        ->andFilterWhere(['like', 'update_file_cinco', $this->update_file_cinco])
        ->andFilterWhere(['like', 'estado_obra', $this->estado_obra])
        ->andFilterWhere(['like', 'status_pedido', $this->status_pedido])
		->andFilterWhere(['like', 'imovel.descritivo_imovel', $this->imovel_id])
		//->andFilterWhere(['like', 'imovel.num_predio', $this->imovel_id])
		->andFilterWhere(['like', 'imovelfraccao.num_fraccao', $this->imovelfraccao_id])
		->andFilterWhere(['like', 'imovel.entidade', $this->entidade])
		->andFilterWhere(['like', 'origempedido.descricao', $this->origempedido_id])
		->andFilterWhere(['like', 'requerente.nome_requerente', $this->requerente_id])			
		->andFilterWhere(['like', 'distrito.nome_distrito', $this->distrito_obras]);
    return $dataProvider;
}

This error happens because the join with “distrito” is missing. For the joinWith function to work, you need to have a function in the Obra model like the following:

public function getDistrito() {
    return $this->hasOne(Distrito::class, ['id' => 'distrito_obra']);
}

Do you have this?

What triggers the error is the following entry in your GridView columns array:

    [
		'attribute' => 'distrito_obras',
        //...
		'filter'=>ArrayHelper::map(\app\models\Distrito::find()->orderBy('id')->asArray()->all(), 'nome_distrito', 'nome_distrito'),
		'value' => 'imovel.distrito.nome_distrito', // Here you are trying to reference the join with distrito from imovel
	],

Also, you code has many redundancies. Leave only one of the following calls:

$query = Obra::find()->alias('im');
$query->joinWith(['imovel', 'imovelfraccao', 'distrito', 'origempedido', 'requerente']);

Even though you are performing other actions based on the user capabilities, these are repeated without need.

For all those filters in andFilterWhere you should add the alias!

    $query->andFilterWhere([
		//self::obra() . 'im.id' => $this->id,
        'im.id' => $this->id, // Here you have alias - Ok.
        'ano_id' => $this->ano_id, // Here you don't - Add it!
    ]);

The best option for your case is to get to know a little more about those relations in Yii2. Might sound painful, but it is worth it!
> Read this documentation <

UAHU - five stars … It worked.
The relations were correct, it was only necessary to add the detail ‘im’, as indicated. The line of code in the ‘obraSearch’ model looked like this,

(…)

	if (Yii::$app->user->can('member')) {
	        // $query = Obra::find()->where(['created_by' => Yii::$app->user->id])->alias('im');
		$query = Obra::find()->where(['im.created_by' => Yii::$app->user->id])->alias('im'); 
		
		$query->joinWith(['imovel', 'imovelfraccao', 'distrito', 'origempedido', 'requerente']);
	}

(…)

NOTE: I had to add the line for $query-> join (…), so that it works correctly.

Great help … I am very grateful. Thanks.