Php 在Laravel 5.4上的BelongTomany关系上使用自定义轴模型
我试图弄清楚如何使用自定义中间模型(透视表)实现多对多关系。这是我的模型:Php 在Laravel 5.4上的BelongTomany关系上使用自定义轴模型,php,laravel,pivot,Php,Laravel,Pivot,我试图弄清楚如何使用自定义中间模型(透视表)实现多对多关系。这是我的模型: banners - id - title - description banner_regions (Pivot) - id - region_id - banner_id - active regions - id - name - slug 雄辩的模型代码: class Banner extends Model { /** * Get all of the regi
banners
- id
- title
- description
banner_regions (Pivot)
- id
- region_id
- banner_id
- active
regions
- id
- name
- slug
雄辩的模型代码:
class Banner extends Model
{
/**
* Get all of the regions for the banner.
*/
public function regions()
{
return $this->belongsToMany('App\Region', 'banner_regions')
->withPivot('active')
->using(BannerRegion::class);
}
}
class BannerRegion extends Model
{
}
class Region extends Model
{
/**
* Get all of the banners for the region.
*/
public function banners()
{
return $this->belongsToMany('App\Banner', 'banner_regions')
->withPivot('active')
->using(BannerRegion::class);
}
}
横幅控制器代码:
class BannerController extends Controller
{
protected $model;
public function __construct(Banner $model)
{
$this->model = $model;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$region = $request->region; // region model instance
// ??
}
}
因此,我这里的问题是如何检索特定区域的横幅?解决方案 我已经更改了代码,现在它可以正常工作了 我将BannerRegion pivot模型更改为
pivot
,而不是模型
:
<?php
namespace App;
use Illuminate\Database\Eloquent\Relations\Pivot;
class BannerRegion extends Pivot
{
// It is just for casting int values into boolean values.
// Useful for JSON responses.
protected $casts = [
'active' => 'boolean',
'for_customers' => 'boolean',
];
}
在我的横幅控制器中,我刚刚添加:
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Region $region)
{
return $this->model->findbyRegionAndActive($region)->get();
}
区域参数由依赖项注入(laravel.com/docs/5.4/routing#route model binding)解决
最后,我的路线:
Route::group(['prefix' => '/regions/{region}'], function()
{
// Banners
Route::resource('banners', 'BannerController', ['only' => 'index']);
});
端点:
/regions/my region/banner
JSON响应:
[
{
"title": "a title...",
"description": "a descritpion...",
"link": "http://localhost",
"for_customers": true
}
]
我有点好奇为什么它是一个id?如果是这样的话,也许
Region::find($Region)->banner()->get()
就可以了。嗨@BagusTesa,看看:)哦,我明白了,那么,你不能直接使用$Region->banner()->get()访问横幅吗?也许您需要先dd($region)
以确保它是所需的项目。@BagusTesa,它确实工作正常。但是,BannerController不是进行$region->banners()->get()
查询(SoC模式)的地方。谢谢我明白了,看来关键在于公共功能索引(Region$Region)
。谢谢分享,看来我对拉威尔的理解现在很枯燥。
[
{
"title": "a title...",
"description": "a descritpion...",
"link": "http://localhost",
"for_customers": true
}
]