laravel显示变量来自第二个表

时间:2017-03-16 08:55:53

标签: php mysql laravel

欢迎!我创建了应用程序,用户拥有自己的笔记(基于外键)。现在在表中我想显示他的名字,但我无法通过它:

试点模式:

class Pilot extends Model
{
  protected $table = 'pilots';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'phone', 'email',
    ];

    public function note() {
      return $this->hasMany(Note::class);
    }

注意型号:

class Note扩展Model

{
  protected $table = 'notes';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'data', 'zadanie', 'uwagi', 'pilot_id',
    ];

    public function pilot() {
      return $this->belongsTo(Pilot::class);
    }

Notes Controller(我想在索引页面中显示导频名称)

public function index(Request $request)

{
    $notes = Note::all();

    $pilots = Pilot::find($id);
    return view('uwagi.index',['notes'=>$notes,'pilots'=>$pilots]);
}

当我通过

传递给它时
{{$pilots->name}} 

我有一个错误undefined $ id。每个注释属于基于外键的pilot_id的用户,该注释表位于注释表中。该pilot_id密钥指的是表导频 - > id和我想在这个id的索引页面名称中显示,但我不知道如何传递它。

关心并感谢您的帮助

2 个答案:

答案 0 :(得分:0)

Controller的索引方法中没有已定义的变量$ id。此外,如果您定义了模型关系,则可以使用Pilot::with('note')->all();获取所需数据 看看这个: https://laravel.com/docs/5.4/eloquent-relationships#eager-loading

但是将pilot_id传递给像

这样的路线的最好方法
Route::get('pilot/{id}', 'NotesController@index')

和索引方法将类似于public function index(Request $request, $pilot_id)

Route::resource('pilot', 'NotesController')

和内部控制器定义show($ pilot_id)方法 而不是使用

$pilot_data = Pilot::with('note')->find($pilot_id);

$pilot_data->note将包含与试用

相关的所有备注

根据代码,毫无疑问在控制器的操作中绑定Request $请求,因为你没有在代码中使用它

答案 1 :(得分:-1)

好的回答是最容易的,因为我想:

控制器:

public function index(Request $request)

{
    $notes = Note::all();

    return view('uwagi.index',['notes'=>$notes,]);
}

刀片:

@foreach ($notes as $note)
{{ $note->pilot->name }}
@endforeach
相关问题