这里我从3种模型横幅、横幅类型及其位置获得数据(横幅类型模型没有问题,所以我跳过它)管理模板是从quickadminpanel生成的。
我的数据结构看起来
标语
Schema::create('banners', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('banner_name')->unique();
$table->string('banner_header');
$table->string('banner_caption')->nullable();
$table->string('banner_btn_txt');
$table->string('banner_btn_link');
$table->string('banner_btn_color');
$table->timestamps();
$table->softDeletes();
});2021_01_15_000003_create_positions_table.php
Schema::create('positions', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('position');
$table->timestamps();
});2021_01_15_000019_add_relationship_fields_to_positions_table.php
Schema::table('positions', function (Blueprint $table) {
$table->unsignedBigInteger('banner_id')->nullable();
$table->foreign('banner_id', 'banner_fk_2983258')->references('id')->on('banners');
});$banner = Banner::get();
$banner_types = BannerType::get();
$positions = Position::with(['banner'])->orderBy("position")->get();
$banner_array = array();
$banner_no_position = array();
foreach ($banner as $banner){
if(Position::where('banner_id',$banner->id)->count() != 0){
$banner_array = array($banner);
}else{
// print_r($banner);
$banner_no_position = array($banner);
}
}我想要做的是分离已经定位的横幅和没有通过创建两个不同的数组来定位的横幅,其中一个称为$banner_array,而另一个$banner_no_position只是显示最后一个对象并丢弃其他对象。
例如,我已经创建了4个横幅,我只定位了2个,然后在$banner_array中得到2个对象,在$banner_no_position数组中只有一个对象,但是它应该有2个或更多的数组,因为我没有定位2个横幅。
我的刀片看起来像https://pastebin.com/hwAqjZ7S,我的完整控制器看起来像https://pastebin.com/LvvLPSNP,它有点凌乱,但是我以后会美化几个函数,我从控制器中使用的函数是索引和newPosition来读取和保存数据。
横幅模型看起来像https://pastebin.com/75nCdBvh,位置模型看起来像https://pastebin.com/vr7GPd8A
发布于 2021-01-21 14:52:55
如果您已经建立了关系,您可以使用该关系来帮助解决以下问题:
$banners = Banner::has('positions')->get();
$banners_without_positions = Banner::doesntHave('positions')->get();在这里,我们使用查询返回所有有任何位置的横幅。然后,我们正在执行另一个查询,以返回所有没有任何位置的横幅。
或者您可以使用withCount方法来获取每个条幅的关系计数,然后使用集合的partition方法将其分解为两个不同的组:
[$banners, $banners_without] = Banner::withCount('positions')
->get()
->partition(fn ($i) => $i->positions_count);这里我们是说,如果这个关系的计数是一个正数(真),那么将它排序到第一组,如果不是(没有位置),将它排序到第二组。您也可以通过只需要加载positions (with('positions')),然后对关系进行计数( $i->positions->count() )就可以做到这一点,但是如果您不需要加载该关系,就不需要加载它并为模型添加水合物。
根据需要调整事物的命名。
Laravel 8.x文档-雄辩的关系-质疑关系的存在 has
Laravel 8.x文档-雄辩-关系-查询关系缺位 doesntHave
Laravel 8.x文档-雄辩的关系.计数相关模型 withCount
Laravel 8.x文档.集合.可用方法 partition
https://stackoverflow.com/questions/65829433
复制相似问题