mercredi 2 décembre 2015

Laravel 5 Eloquent relationship get the data

I have two table.

(Persons)

+------+------+ 
| id   | name | 
+------+------+ 
|  1   | John | 
+------+------+
|  2   |Albert| 
+------+------+

(Motors)

+------+------+------+ 
| id   | name |  age | 
+------+------+------+ 
|   1  |   1  |  20  | 
+------+------+------+ 
|   2  |   2  |  21  | 
+------+------+------+ 
|   3  |   1  |  20  | 
+------+------+------+

In "motors.name" i have the ids of people.

I have two models.

(Motors)

class Motors extends Eloquent
{
    public function person(){
        return $this->hasMany('App\Persons', 'id');
    }    
}

(Persons)

class Persons extends Eloquent
{
    protected $table = 'persons';
    public function motors(){
        return $this->belongsTo('App\Motors', 'name', 'id');
    }    
}

1 controller

class PrototypeController extends Controller
{
    public function names(Request $request) {
        $res = Motors::get()->person->name;
        return view('pages.prototype', compact('res'));
    }
}

1 view

<ul class="list">
    @foreach ($res as $row)     
        @if (!empty($row->name))
            <li class="list-group-item">
                {!! $row->name !!}
            </li>
        @endif
    @endforeach
</ul>

I'd like tosee the rerelational dara in view, not the ids. How can it be solved?

This code isn't good:

$res = Motors::get()->person->name;

Thanks in advance for your help.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire