mic*_*cky 13 javascript php laravel
产品具有一对多的关系,'productbrand',表productbrand和productbrand具有一对一的关系,'品牌',与表品牌.表品牌有一个专栏,'品牌'.我可以访问该产品的品牌.可以正确访问所有其他类别,用户名等.
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;
}
Run Code Online (Sandbox Code Playgroud)
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);
}
}
});
Run Code Online (Sandbox Code Playgroud)
这样我只能得到一个品牌.我也试过以下方式,但失败了.
在控制器中:
$getbrands = $show->productbrand;
echo json_encode(array('status' => TRUE, 'show' => $show, 'username' => $username, 'category' => $category, 'getbrands' => $getbrands));
Run Code Online (Sandbox Code Playgroud)
在Ajax中:
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
}
Run Code Online (Sandbox Code Playgroud)
为什么要声明所有这些变量:
$category = $show->category->category;
$username = $show->user->username;
$getbrands = $show->productbrand;
Run Code Online (Sandbox Code Playgroud)
如果category,user,productbrand和brands是与产品的模型关系,并从类别,用户的用户名等获取类别.
而是与'与'保持关系;
public function show(Request $request)
{
if($request->ajax())
{
$id = $request->id;
if($id)
{
$show = Product::where(['product_id'=>$id])->with('category')
->with('user')
->with('productbrand.brand') // product has onetomany relation 'productbrand' with table productbrand and productbrand has onetoone relation 'brand' with table brand
->first();
if($show)
{
echo json_encode(array('status' => TRUE, 'show'=>$show)); die;
}
}
}
echo json_encode(FALSE);die;
Run Code Online (Sandbox Code Playgroud)
在JavaScript中:
if(res.status == true)
{
var result = 'Category: ' + res.show.category.category + '<br>' +
'Product by: ' + res.show.user.username + '<br>' +
'Price: ' + res.show.price + '<br>' +
'Price type: ' + res.show.price_type + '<br>' +
'Product Views: ' + res.show.views + '<br>';
$('#result').html(result);
}
}
});
Run Code Online (Sandbox Code Playgroud)
产品与表品牌和产品品牌有关系,产品品牌与表品牌有关联的"品牌".表品牌有一个专栏'品牌'.并且我无法访问该产品的品牌. 像这样访问品牌.
var result = 'Brands: ';
for(var i=0; i<res.show.productbrand.length; i++)
{
result += res.show.productbrand[i].brand.brand;
}
Run Code Online (Sandbox Code Playgroud)