I'm trying to fetch data from one to many relationship via Ajax Call.
My RestaurantOffer_table table:
id | restaurant_offer_id | tableName | fromNr | toNr
-----------------------------------------------------
1 | 1 | table1 | 1 | 4
-----------------------------------------------------
2 | 1 | table2 | 5 | 10
Now, I have to fetch these data from this table.
Model RestaurantOffer.php
class RestaurantOffer extends Model
{
protected $guarded = [];
public function restaurant_offer_table()
{
return $this->hasMany(RestaurantOffer_table::class);
}
}
Model RestaurantOffer_table.php
class RestaurantOffer_table extends Model
{
protected $guarded = [];
public function restaurantoffer()
{
return $this->belongsTo(RestaurantOffer::class);
}
}
Controller RestaurantOffersController.php
function fetchdata(Request $request)
{
$id = $request->input('id');
$data = RestaurantOffer::find($id);
$output = array(
'monthlySum' => $data->monthlySum,
'userProfitPercentage' => $data->userProfitPercentage,
.......................
);
if($request->ajax()) {
echo json_encode($output);
}
}
In this controller, all my data from RestaurantOffer model are fetching as well, but how to fetch data also from RestaurantOffer_table model using the same function in controller.
View Ajax function:
$(document).on('click', '.edit', function(){
var id = $(this).attr("id");
var image_index= $(this).attr('data-index');
$('#form_output').html('');
$.ajax({
url: "{{route('restaurantOffers.fetchdata')}}",
method: 'get',
data: {id:id},
dataType: 'json',
success:function(data)
{
$('#getMonthlySum').val(data.monthlySum);
$('#userProfitPercentage').val(data.userProfitPercentage);
$.........
$('#contract_id').val(id);
$('#editContract').modal('show');
$('#action').val('Speichern');
$('.modal-title').text('Daten aktualisieren');
$('#button_action').val('update');
}
});
So, the question is, how to fetch data from RestaurantOffer_table for each row of RestaurantOffer via Ajax call. e.g
Restaurant 1 -> table1 | 1 | 4
table2 | 5 | 10
Thank you in advance.
CodePudding user response:
You have defined the Relation in model. Thats good. But did not used while fetching in controller.
You have mention the relation function in with()
method while doing model query like below
$data = RestaurantOffer::with('restaurant_offer_table')->where('id',$id)->first();
It will call eagerloading method in laravel.
But you can also use that relation method after the elequent query.
$data = RestaurantOffer::find($id);
$data->restaurant_offer_table; // like this.
But it is not eagerloaded and you can not use this function in js file so you have to eager load the data.