【发布时间】:2016-12-19 09:33:47
【问题描述】:
Product 与 table productbrand 具有一对多关系“productbrand”,productbrand 与 table brand 具有一对一关系“brand”。表品牌有一个列,“品牌”。我可以访问产品的品牌。所有其他类别、用户名等都可以正常访问。
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
}
【问题讨论】:
-
试试这个:$show=Product::where(['product_id'=>$id])->with('productbrand')->first();
-
@Autista_z 问题在于使用 javascript 访问。
-
我正在写一个答案,但我注意到您的代码非常非常奇怪。我真的建议你看看 www.laracasts.com 的课程,你会学到很多关于 laravel 的知识。祝你好运。
标签: javascript php laravel