我正在嘗試通過 Ajax Call 從一對多關系中獲取資料。
我的 RestaurantOffer_table 表:
id | restaurant_offer_id | tableName | fromNr | toNr
-----------------------------------------------------
1 | 1 | table1 | 1 | 4
-----------------------------------------------------
2 | 1 | table2 | 5 | 10
現在,我必須從這個表中獲取這些資料。
模型餐廳Offer.php
class RestaurantOffer extends Model
{
protected $guarded = [];
public function restaurant_offer_table()
{
return $this->hasMany(RestaurantOffer_table::class);
}
}
模型餐廳Offer_table.php
class RestaurantOffer_table extends Model
{
protected $guarded = [];
public function restaurantoffer()
{
return $this->belongsTo(RestaurantOffer::class);
}
}
控制器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);
}
}
在這個控制器中,我從RestaurantOffer模型中獲取的所有資料也都在獲取,但是如何使用控制器中的相同函式從RestaurantOffer_table模型中獲取資料。
查看 Ajax 函式:
$(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');
}
});
所以,問題是,如何通過 Ajax 呼叫從RestaurantOffer_table中為 RestaurantOffer的每一行獲取資料。例如
Restaurant 1 -> table1 | 1 | 4
table2 | 5 | 10
先感謝您。
uj5u.com熱心網友回復:
您已經在模型中定義了關系。那挺好的。但在控制器中獲取時沒有使用。
with()您在進行模型查詢時提到了方法中的關系函式,如下所示
$data = RestaurantOffer::with('restaurant_offer_table')->where('id',$id)->first();
它將呼叫 laravel 中的 eagerloading 方法。
但是您也可以在 elequent 查詢之后使用該關系方法。
$data = RestaurantOffer::find($id);
$data->restaurant_offer_table; // like this.
但它不是預先加載的,您不能在 js 檔案中使用此功能,因此您必須預先加載資料。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/424071.html
