Produkt hat eine Eins-zu-viele-Beziehung, 'Produktmarke', mit Tabelle Produktmarke und Produktmarke hat eine Eins-zu-Eins-Beziehung, 'Marke', mit Tischmarke. Tischmarke hat eine Spalte, "Marke". Und ich kann auf die Marke des Produkts zugreifen. Auf alle anderen Kategorien, Benutzernamen usw. wird korrekt zugegriffen.Zugriff auf Laravel-Beziehungen in JavaScript-Code
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 und 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);
}
}
});
So kann ich nur eine Marke bekommen. Ich habe auch den folgenden Weg versucht, aber gescheitert.
In der Steuerung:
$getbrands = $show->productbrand;
echo json_encode(array('status' => TRUE, 'show' => $show, 'username' => $username, 'category' => $category, 'getbrands' => $getbrands));
In 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
}
starten: $ show = Artikel :: wo ([ 'product_id' => $ id]) -> mit ('productbrand') -> ersten(); –
@Autista_z Das Problem ist der Zugriff mit Javascript. – micky
Ich schrieb eine Antwort, aber ich habe bemerkt, dass Ihr Code sehr, sehr seltsam ist. Ich empfehle Ihnen, einen Blick auf www.laracasts.com zu werfen. Sie werden viel über Laravel lernen. Viel Glück. –