Нет данных, возвращаемых withCount в запросе ads / ad_comments? - PullRequest
0 голосов
/ 24 февраля 2020

В Laravel 6.14.0 У меня есть запрос объявлений и связанных с ними рекламных объявлений с использованием withCount, и в данных результатов я не вижу никаких данных с возвращениями withCount:

$ads             = Ad
    ::with('adReportAbuses.user')
    ->with('adCategories.category')
    ->with('latestAdComment') // THAT WORKS OK
    ->withCount('adComments') // THAT DOES NOT WORK
    ->getByTitle($this->filter_title)
    ->getByStatus('A')
    ->getByAdType($this->filter_ad_type)
    ->getByCategoryId($this->filter_category_id)
    ->where('ads.id', 1) // DEBUGGING
    ->onlyWithImagesCount($this->filter_only_with_images)
    ->onlyWithPhoneDisplay($this->filter_only_with_phone_display)
    ->getUserByStatus('A')
    ->onlyWithUsersPhoneNoneEmpty($this->filter_only_with_phone_display)
    ->leftJoin('users', 'users.id', '=', 'ads.creator_id')
    ->leftJoin('ad_categories', 'ad_categories.ad_id', '=', 'ads.id')
    ->orderBy($this->order_by, $this->order_direction)
    ->select(
        'ads.*',
        'users.name as creator_username',
        'users.email as creator_email',
        'users.phone as creator_phone'
    )
    ->offset($limit_start)
    ->take($ads_per_page)
    ->distinct('ads.id')
    ->get();

Проверка sql Я вижу I запрос данных sda_ad_comments (все запросы приведены ниже):

   SELECT * 
    FROM `sda_ad_comments` 
    WHERE `sda_ad_comments`.`ad_id` in (1) 
    ORDER BY `created_at` desc, `id` desc 

, и у меня есть последний элемент AdComment в данных результатов (но на самом деле я вижу, что все связанные строки читаются, а не последние 1 строки) и нет данных для withCount:

   SELECT distinct `sda_ads`.*, `sda_users`.`name`     AS `creator_username`, `sda_users`.`email`     AS `creator_email`, `sda_users`.`phone`     AS `creator_phone` 
    FROM `sda_ads` 
    LEFT JOIN `sda_users` on `sda_users`.`id` = `sda_ads`.`creator_id` 
    LEFT JOIN `sda_ad_categories` on `sda_ad_categories`.`ad_id` = `sda_ads`.`id` 
    WHERE `sda_ads`.`status` = 'A'     AND `sda_ads`.`id` = '1'     AND `sda_users`.`status` = 'A' 
    ORDER BY `price` asc, `price` desc limit 4 offset 0 


   SELECT * 
    FROM `sda_ad_report_abuses` 
    WHERE `sda_ad_report_abuses`.`ad_id` in (1) 
    ORDER BY `created_at` desc, `created_at` asc 


   SELECT * 
    FROM `sda_users` 
    WHERE `sda_users`.`id` in (1, 2) 


   SELECT * 
    FROM `sda_ad_categories` 
    WHERE `sda_ad_categories`.`ad_id` in (1) 



   SELECT * 
    FROM `sda_categories` 
    WHERE `sda_categories`.`id` in (2, 4) 
    ORDER BY `name` asc 


   SELECT * 
    FROM `sda_ad_comments` 
    WHERE `sda_ad_comments`.`ad_id` in (1) 
    ORDER BY `created_at` desc, `id` desc 


   SELECT * 
    FROM `sda_ad_images` 
    WHERE `sda_ad_images`.`ad_id` = '1'     AND `sda_ad_images`.`main` = '1' limit 1 


   SELECT * 
    FROM `sda_ad_images` 
    WHERE `sda_ad_images`.`ad_id` = '1' 
    ORDER BY `id` asc limit 1 

app / AdComment. php:

<?php
namespace App;

use DB;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use App\library\MyFuncsClass;
use App\User;
use App\Ad;

class AdComment extends Model
{

    protected $fillable = [ 'ad_id', 'parent_ad_comment_id', 'user_id', 'approved',' comment', 'rating'];
    protected $table = 'ad_comments';
    protected $primaryKey = 'id';
    public $timestamps = false;

//    protected $with = ['ad'];

    protected static function boot()
    {
        parent::boot();
        static::addGlobalScope('order', function (Builder $builder) {
            $builder->orderBy('id', 'desc');
        });
    }



    public function ad(){
        return $this->belongsTo('App\Ad', 'ad_id','id');
    }

    public function children()
    {
        return $this->hasMany('App\AdComment', 'parent_ad_comment_id', 'id');
    }

app / Ad. php:

<?php

namespace App;

use DB;
use Illuminate\Database\Eloquent\Model;
use App\library\MyFuncsClass;
use Illuminate\Validation\Rule;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Str;
use Webpatser\Uuid\Uuid;
use App\AdComment;
use Cviebrock\EloquentSluggable\Sluggable;



class Ad extends Model
{
    use Sluggable;

    protected $table = 'ads';
    protected $primaryKey = 'id';
    public $timestamps = false;

    protected $fillable = [
        'title', 'slug', 'phone_display', 'published', 'price', 'ad_type', 'expire_date', 'description', 'creator_id'  ];

    public function sluggable()
    {
        return [
            'slug' => [
                'source' => 'title'
            ]
        ];
    }

    protected static function boot()
    {

        self::creating(function ($model) {
            $model->ad_token = (string)Uuid::generate();   }
        );

        parent::boot();

        static::deleting(function($ad) {
            foreach ( $ad->adImages()->get() as $nextAdImage ) {
                $ad_image_image_path = AdImage::getAdImagePath($nextAdImage->ad_id, $nextAdImage->image);
                MyFuncsClass::deleteFileByPath($ad_image_image_path, true);
            }
        });

        static::addGlobalScope('order', function (Builder $builder) {
            $builder->orderBy('price', 'desc');
        });

    }

    public function scopeGetBySlug($query, $slug = null)
    {
        if (empty($slug)) {
            return $query;
        }
        return $query->where(with(new Ad)->getTable() . '.slug', $slug);
    }

    public function scopeGetByCreatorId($query, $creator_id = null)
    {
        if (empty($creator_id)) {
            return $query;
        }
        return $query->where(with(new Ad)->getTable() . '.creator_id', $creator_id);
    }

    public function adCategories()
    {
        return $this->hasMany('App\AdCategory', 'ad_id', 'id');
    }

    public function adReportAbuses()
    {
        return $this->hasMany('App\AdReportAbuse', 'ad_id', 'id')->orderBy('created_at', 'desc');
    }

    public function adComments()
    {
        return $this->hasMany('App\AdComment', 'ad_id', 'id')->orderBy('created_at', 'desc');
    }
    public function latestAdComment()
    {
        return $this->hasOne('App\AdComment')->latest();
    }

Неправильно ли настроены мои модели? Почему нет данных без данных?

Спасибо!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...