gpt4 book ai didi

php - Laravel Datatable ManyToMany 与多个表的关系

转载 作者:可可西里 更新时间:2023-11-01 06:38:15 25 4
gpt4 key购买 nike

Offer.php #model

use App\OfferCategory;
use App\OfferCountries;
use App\OfferCreative;
use App\OfferTools;
use App\OfferTraffic;

class Offer extends Model {
public function offer_countries() {
return $this->belongsToMany(OfferCountries::class);
}

public function offer_categories() {
return $this->belongsToMany(OfferCategory::class);
}

public function offer_creatives() {
return $this->hasMany(OfferCreative::class);
}

public function offer_tools() {
return $this->hasMany(OfferTools::class);
}

public function offer_traffic() {
return $this->hasMany(OfferTraffic::class);
}

public function platforms() {
return $this->hasMany(Platform::class);
}

OfferController.php

 public function getMediaData() {
// $model = Offer::with('offer_traffic');
// return DataTables::eloquent($model)
// ->addColumn('traffic', function (Offer $user) {
// return $user->offer_traffic->map(function($post) {
// return str_limit($post->allowed_traffic, 30, '...');
// })->implode('<br>');
// })
// ->toJson();

return datatables(DB::table('offers'))->toJson();
}

我想使用 offer.php 中给出的所有关系表和数据表中的图像。我已经尝试在 Controller 中使用注释代码但无法获取请帮助我知道我做错了什么。

OfferCountries.php #model

使用App\Offer;

class OfferCountries extends Model {

function offers() {
return $this->belongsToMany(Offer::class);
}
}

 Database schema

最佳答案

这是我的做法,

在 Offer.php 中

 class Offer extends Model {
public function offer_countries() {
return $this->hasMany(OfferOfferCountries::class,'offer_id','id');
}

public function offer_categories() {
return $this->hasMany(OfferOfferCategories::class,'offer_id','id');
}

public function offer_creatives() {
return $this->hasMany(OfferCreative::class,'offer_id','id');
}

public function offer_tools() {
return $this->hasMany(OfferTools::class,'offer_id','id');
}

public function offer_traffic() {
return $this->hasMany(OfferTraffic::class,'offer_id','id');
}

public function platforms() {
return $this->hasMany(Platform::class,'offer_id','id');
}
}

在 OfferOfferCountries.php 中

class OfferOfferCountries extends Model {
public function countryDetail(){
return $this->belongsTo(OfferCountries::class,'offercountry_id','id');
}
}

在 OfferOfferCategory.php 中

class OfferOfferCategory extends Model {
public function categoryDetail(){
return $this->belongsTo(OfferCategory::class,'offercategory_id','id');
}
}

现在在 Controller 中

public function getMediaData() {
$data = Offer::with('offer_countries.countryDetail','offer_categories.categoryDetail','offer_creatives','offer_tools','offer_traffic','platforms')->get();

echo '<pre>';
print_r($data);

}

这应该为您提供包含所有内容的对象数组。您可以使用数据透视表,但我喜欢这种方式。

关于php - Laravel Datatable ManyToMany 与多个表的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56390036/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com