I cannot access object property. Laravel/Eloquent ORM

Asked

Viewed 1,822 times

4

I cannot access the properties of the related object. Well, I have a class calling for FileClass, she has the following relationship with class FileServico:

Fileclass.php

public function fileServico(){
    return $this->hasMany('FileServico','id_file','id_file');
}

Fileservico.php

public function file(){
    return $this->belongsTo('FileClass','id_file','id_file');
}

In my controller I recover the values as follows:

Reservacontroller.php

public function getIndex(){
    $fileClass = FileClass::with(['FileServico'])->get();
    return View::make('home')->with('fileClass',$fileClass);
}

However, in the view I cannot access the objects of the relationship, below I list some ways to access that I tried:

@foreach($fileClass as $f)
    $f->id_servico; //Tentei assim
    $f->file_servico->id_servico //Tentei assim
    $f->fileServico->id_servico; //Assim também
    $f->id_servico //Assim também
    $f->fileServico['id_servico'] //Como array também
    $f->fileServico[0]['id_servico'] //Assim...
@endforeach

Understanding better, a file can have several file_servico, if I just give a print_r() in $fileClass which is the object q returns to view it does not visualize the related object, but if I give a print_r() in an iterated object with foreach and try to access its separate property, it accesses normally $f->fileServico.

3 answers

3


The FileClass has a List of FileServico ($f->fileServico) in case can not be accessed without a for or a foreach. If it were unlike FileServico for Fileclass ai would be right what you report in the question. Below an example to clear.

Suggesting a minimal example:

//Tabela fileclass
CREATE TABLE `fileclass` (
  `id_file` int(11) NOT NULL AUTO_INCREMENT,
  `desc` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id_file`),
  UNIQUE KEY `id_file_UNIQUE` (`id_file`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8
//Tabela fileservico
CREATE TABLE `fileservico` (
  `id_servico` int(11) NOT NULL AUTO_INCREMENT,
  `id_file` int(11) DEFAULT NULL,
  `desc` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id_servico`),
  KEY `id_file_key_idx` (`id_file`),
  CONSTRAINT `id_file_key` FOREIGN KEY (`id_file`) 
  REFERENCES `fileclass` (`id_file`) 
  ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8

Dados Exemplos

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

Models

class FileClass extends Eloquent 
{
    public $table      = 'fileclass'; 
    public $primaryKey = 'id_file';
    public $timestamps = false;
    public function fileServico(){
        return $this->hasMany('FileServico','id_file','id_file');
    }
}
class FileServico extends Eloquent {
    public $table      = 'fileservico'; 
    public $primaryKey = 'id_servico';
    public $timestamps = false;
    public function file(){
        return $this->belongsTo('FileClass','id_file','id_file');
    }
}

Eloquent accessing relationship with

$files = FileClass::with('FileServico')->get();
foreach ($files as $file) {
    echo $file->id_file.' '.$file->desc;
    echo '<br>';
    $servicos = $file->FileServico;         
    foreach ($servicos as $servico) 
    {
        echo $servico->id_servico.' '.$servico->desc;
        echo '<br>';
    }
    echo '<br>';
    echo '<br>';
}

Debug:

select * from `fileclass`
Array ( [0] => 1 [1] => 2 )
select * from `fileservico` where `fileservico`.`id_file` in (?, ?)

//id_file = 1
1 File 1
   1 Servico1
   2 Servico2

//id_file = 2
2 File 2
  3 Servico3

1

Object returned if I access $f->fileServico, which is the relationship.

Illuminate\Database\Eloquent\Collection Object
(
[items:protected] => Array
    (
        [0] => FileServico Object
            (
                [table:protected] => file_servico
                [fillable:protected] => Array
                    (
                        [0] => id_servico
                    )

                [rules:protected] => Array
                    (
                    )

                [primaryKey:protected] => id_file
                [connection:protected] => 
                [perPage:protected] => 15
                [incrementing] => 1
                [timestamps] => 1
                [attributes:protected] => Array
                    (
                        [id_servico] => 4
                        //Aqui ficam os campos da tabela...
                    )

                [original:protected] => Array
                    (
                        [id_servico] => 4
                        //Aqui ficam os campos da tabela...
                    )

                [relations:protected] => Array
                    (
                    )

                [hidden:protected] => Array
                    (
                    )

                [visible:protected] => Array
                    (
                    )

                [appends:protected] => Array
                    (
                    )

                [guarded:protected] => Array
                    (
                        [0] => *
                    )

                [dates:protected] => Array
                    (
                    )

                [touches:protected] => Array
                    (
                    )

                [observables:protected] => Array
                    (
                    )

                [with:protected] => Array
                    (
                    )

                [morphClass:protected] => 
                [exists] => 1
            )

    )

)

1

Access to protected property was not possible, so I had to make some modifications to be able to run. Well:

In the controller I added the toArray method, so it returns me everything as array:

$fileClass = FileClass::with(['FileServico'])->get()->toArray();

Next, I recovered in the view the values iterating with two foreach, see:

@foreach($fileClass as $file)
    @foreach($file['file_servico'] as $f)
        <tr>
            <td>{{ $f['id_servico'] }}</td>
        </tr>
    @endforeach
@endforeach

It loses a bit of elegance by not accessing as an object, but I got what I wanted, who has another more practical means, I would appreciate it if you could share.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.