【发布时间】:2022-01-19 20:04:25
【问题描述】:
我使用 Laravel 8、Eloquent 和 Datatables 已经有几天了。我实际上找到了如何用我的一个表和 Eloquent 来显示一个数据表。
我现在的问题是我需要在一列中显示名称(您可以在“称谓”表中找到)而不是他的外键。
screenshot of the actual result of my datatables
这是我实际拥有的屏幕截图,我的目的是显示您可以在我以红色显示的第 2 列的“称谓”表中找到的“abrege”(“App CVI”和“App参与”),而不是外键。
我的代码实际上是:
我的“SousParcelle”模型:
class SousParcelle extends Model
{
use HasFactory;
protected $table = 'sous_parcelles';
protected $fillable = ['id',
'parcelle_id',
'cepage_id',
'appellation_cvi_id',
'dist_entre_rang',
'dist_sur_rang',
'densite_theorique',
'superficie',
'annee_plantation',
'modification_par',
'modification_le',
'validee',
'affectation_appellation_id',
'affectation_superficie'];
public function appellation(){
return $this->belongsTo(Appellation::class, 'affectation_appellation_id', 'id');
}
}
我的“称谓”模型:
class Appellation extends Model
{
use HasFactory;
protected $table = 'appellations';
protected $fillable = ['id', 'libelle', 'abrege', 'siqo_id'];
public function sousparcelles(){
return $this->hasMany(Appellation::class, 'affectation_appellation_id', 'id');
}
}
我的“SousParcellesController”数据表控制器:
class SousParcellesController
{
public function index()
{
return view('welcome');
}
public function getSousParcelles(Request $request)
{
if ($request->ajax()) {
$query = SousParcelle::with(['appellation' => function($query){
$query->select('abrege');
}]);
return DataTables::of($query)
->addIndexColumn()
->addColumn('App engagee', function(SousParcelle $sousparcelles){
return $sousparcelles->appellations()->abrege;
})
->make(true);
}
}
}
我的观点脚本“welcome.blade.php”:
<table id="sousparcelles" class="table table-bordered yajra-datatable">
<thead>
<tr>
<th>Référence Cadastrale</th>
<th>Commune</th>
<th>Plantation</th>
<th>Cepage</th>
<th>App CVI</th>
<th>Sup CVI</th>
<th>App engagee</th>
<th>Sup engagee</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script type="text/javascript">
function load_table(appellation_id) {
if ($.fn.dataTable.isDataTable('.yajra-datatable')) {
$('.yajra-datatable').DataTable().destroy();
}
var table = $('.yajra-datatable').DataTable({
processing: true,
serverSide: true,
searching: true,
ajax: "{{ route('sousparcelles.liste') }}",
columns: [
{data: 'dist_entre_rang', name: 'dist_entre_rang'},
{data: 'parcelle_id', name: 'parcelle_id'},
{data: 'annee_plantation', name: 'annee_plantation'},
{data: 'cepage_id', name: 'cepage_id'},
{data: 'appellation_cvi_id', name: 'appellation_cvi_id', type: 'selection'},
{data: 'superficie', name: 'superficie'},
{data: 'affectation_appellation_id', name: 'appellations.abrege'},
{data: 'affectation_superficie', name: 'affectation_superficie'},
]
});
}
$(function () {
load_table(5);
});
function change_appellation() {
load_table(6);
}
</script>
有人可以告诉我这种关系沟通吗?
【问题讨论】:
-
你的人际关系中有很多错误。首先要跳出来的是
Appelation::sousparcelles()中的类名不正确,模型中的Sousparcelle::appelation()和控制器中的$sousparcelles->appellations()之间存在差异。
标签: laravel eloquent datatables laravel-8