【发布时间】:2020-04-13 02:48:26
【问题描述】:
正如标题所说,我的 Field 模型和 application_fields 表有不同的名称。我已经将 Field 模型上的表名设置为正确的表名。我有另一个模型 Application 及其控制器 ApplicationController。在 ApplicationController 的 index 方法中,我试图检索应用程序及其字段。 Field模型与Application有belongsTo关系,Application模型与Field有hasMany关系。
代码似乎可以工作,除了它从应用程序表中提取行的值。因此,如果应用程序表有以下行:
1 'AppOne' '一个应用'
2 'AppTwo' '另一个应用程序'
3 'AppThree' '第三个应用程序'
AppOne、AppTwo 和 AppThree 作为字段的值返回。
谁能给我一些建议?
这是他们的代码(我只复制了与问题相关的内容,而不是整个文件):
应用模型:
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'application_fields';
public function fields()
{
return $this->hasMany('App\Field');
}
场模型:
public function application()
{
return $this->belongsTo('App\Application');
}
应用控制器:
/**
* Display the dashboard for a single application.
*
* @param String $id
* @return View
*/
public function show( $id )
{
$app = Application::where('id', $id)->first();
$fields = $app::with('application_fields')->get();
return view('applications.show', [
'application' => $app,
'fields' => $fields,
]);
}
查看(我去掉了 HTML):
{{ $application->name }}
{{ $application->description }}
@foreach($fields as $field)
{{ $field->name}}
@endforeach
对于我做错的任何建议,我将不胜感激。谢谢
【问题讨论】:
标签: laravel eloquent model laravel-6