我正在尝试读取嵌套数组并在刀片表中显示该值。
以下是我在视图中看到的数据:
{
"sub_issue_id": 2,
"sub_issue": "Publick speaking",
"sub_issue_desc": "This sub issue tracks the progress related to public speaking. ",
"sub_issue_status": 1,
"sub_issue_main_issue_id": 1,
"sub_issue_user_id": 1,
"created_at": "2015-01-18 13:45:34",
"updated_at": "2015-01-18 13:45:34",
"main_issue": [
{
"main_issue_id": 1,
"main_issue": "Commuincations",
"main_issue_desc": "This main task tracks progress on communications. ",
"main_issue_status": 1,
"main_issue_user_id": 1,
"created_at": "2015-01-18 00:20:29",
"updated_at": "2015-01-18 00:20:29"
}
]
}
{
"sub_issue_id": 3,
"sub_issue": "Emails",
"sub_issue_desc": "This subissue tracks the progress related to emails. ",
"sub_issue_status": 1,
"sub_issue_main_issue_id": 1,
"sub_issue_user_id": 1,
"created_at": "2015-01-18 13:51:48",
"updated_at": "2015-01-18 13:51:48",
"main_issue": [
{
"main_issue_id": 1,
"main_issue": "Commuincations",
"main_issue_desc": "This main task tracks progress on communications. ",
"main_issue_status": 1,
"main_issue_user_id": 1,
"created_at": "2015-01-18 00:20:29",
"updated_at": "2015-01-18 00:20:29"
}
]
}
基本上我需要阅读数组" main_issue"并显示" main_issue"的值属性(在上面的数据"通信")
以下是我尝试的选项:
@foreach( $subIssues as $subIssue )
{{ $subIssue }}
<tr>
{{--<td>{{ $subIssue->main_issue[0]->main_issue }}</td>--}}
{{--<td>{{ $subIssue->main_issue->first()->main_issue }} </td>--}}
{{--<td>{{ $subIssue->main_issue->firstRow->get(0)->main_issue }} </td>--}}
Here are the model & controller code..public function SubIssue()
{
return $this->belongsTo('App\Models\Issues\SubIssue', 'main_issue_id','sub_issue_main_issue_id'); /**
* Relation between sub issue and main issue
*/
public function MainIssue()
{
return $this->hasMany('App\Models\Issues\MainIssue', 'main_issue_id', 'sub_issue_main_issue_id');
}
$mainIssues = $mainIssue->where('main_issue_user_id', $id)->get();
//dd($mainIssues->toArray());
return view('issues.mainIssues.mainIssues', compact('mainIssues'));
}enter code here
答案 0 :(得分:0)
尝试以下方法:
{{ $subIssue->MainIssue->main_issue }}
考虑将camelCase用于方法名称,这可以使代码更易于阅读。上面一行中的MainIssue是SubIssue类的MainIssue()函数,如果你像Laravel那样遵循PSR-1,它应该是mainIssue():http://www.php-fig.org/psr/psr-1/
另一个提示(来自个人经验):不要在所有字段名称中重复表名。 $ main_issue-&gt; name($ main_issue-&gt; status,ect)比main_issue-&gt; main_issue更容易阅读。
编辑:您的关系方法中的关键字看起来是相反的。 Laravel docs表示第二个参数是外键,第三个参数是本地键。 (尽管这些术语似乎在“一对一”部分的一个示例中混淆)尝试以下内容 -
//In SubIssue model
mainIssue()
{
return $this->belongsTo('App\Models\Issues\MainIssue', 'sub_issue_main_issue_id', 'main_issue_id');
}
//In MainIssue model
public function subIssue()
{
return $this->hasMany('App\Models\Issues\SubIssue', 'sub_issue_main_issue_id', 'main_issue_id');
}
我找到了像&sub'issue_main_issue_id&#39;很难遵循,如果你使用名为&#39; id&#39;对于您的主键,&#39; table_name_id&#39; (例如main_issue_id)对于您的外键,您可以利用Laravel的约定(您不必指定在关系中使用的键)。
另请注意:如果您使用自己的主键,请务必在模型中设置$ primaryKey变量:
protected $primaryKey = 'main_issue_id';