產品與表格品牌具有一對多關係'productbrand',產品品牌與表格品牌具有一對一關係'品牌'。表品牌有一個專欄,'品牌'。而且我能夠訪問產品的品牌。所有其他類別,用戶名等都可以正確訪問。在JavaScript代碼中訪問Laravel關係
public function show(Request $request)
{
if($request->ajax())
{
$id = $request->id;
if($id)
{
$show = Product::where(['product_id'=>$id])->first();
$category = $show->category->category;
$username = $show->user->username;
$getbrands = $show->productbrand;
foreach($getbrands as $getbrand)
{
$brand=$getbrand->brand->brand;
}
if($show)
{
echo json_encode(array('status' => TRUE, 'show' => $show, 'username' => $username, 'category' => $category, 'brand' => $brand)); die;
}
}
}
echo json_encode(FALSE);die;
}
的Ajax和jQuery:
$.ajax({
type: "POST",
url: "{{url('/product/show')}}",
data: {id:id},
success: function (data) {
var res = $.parseJSON(data);
if(res.status == true)
{
var result = 'Category: ' + res.category + '<br>' +
'Product by: ' + res.username + '<br>' +
'Brands: ' + res.brand + '<br>' +
'Price: ' + res.show.price + '<br>' +
'Price type: ' + res.show.price_type + '<br>' +
'Product Views: ' + res.show.views + '<br>';
$('#result').html(result);
}
}
});
這樣我能得到只有一個品牌。我也嘗試了以下方法,但失敗了。
在控制器:
$getbrands = $show->productbrand;
echo json_encode(array('status' => TRUE, 'show' => $show, 'username' => $username, 'category' => $category, 'getbrands' => $getbrands));
在阿賈克斯:
for(var i=0; i<res.getbrands.length; i++)
{
var brands=res.getbrands[i].brand.brand; //First 'brand' is relation and second is the brand I am trying to access
}
嘗試這種情況: $顯示=產品::其中([ 'PRODUCT_ID'=> $ ID]) - >用( 'productbrand') - >第一(); –
@Autista_z問題是使用JavaScript訪問。 – micky
我正在寫一個答案,但我注意到你的代碼非常非常奇怪。我真的建議你看一下www.laracasts.com課程,你會學到很多關於laravel的知識。祝你好運。 –