【问题标题】:laravel display variable from second tablelaravel 显示第二个表中的变量
【发布时间】:2017-08-07 08:16:37
【问题描述】:

欢迎!我制作了用户拥有自己笔记的应用程序(基于外键)。现在在表格中我想显示他的名字但我不能通过它:

试点模型:

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);
    }

笔记模型:

类注释扩展模型

{
  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}} 

我有一个未定义的 $id 错误。每个便笺基于便笺表中的外键 Pilot_id 属于用户。这个 Pilot_id 键是指表 Pilots -> id,我想在这个 id 的索引页面名称中显示,但我不知道如何传递它。

问候并感谢您的帮助

【问题讨论】:

标签: php mysql laravel


【解决方案1】:

Controller 的 index 方法中没有定义变量 $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 将包含所有连接到 Pilot 的笔记

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

【讨论】:

  • App\Http\Controllers\NotesController::index() 缺少参数 2
  • 从索引方法中移除Request参数,只留下$pilot_id
【解决方案2】:

好的答案是我想的最简单的:

控制器:

public function index(Request $request)

{
    $notes = Note::all();

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

刀片:

@foreach ($notes as $note)
{{ $note->pilot->name }}
@endforeach

【讨论】:

  • 除非它根本不匹配问题(更不用说这是您自己的问题),因为您粘贴的代码表明您只需要给定 Pilot 的注释,而不是全部。
猜你喜欢
  • 2020-12-04
  • 2020-04-28
  • 2019-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-03
  • 1970-01-01
相关资源
最近更新 更多