Выбрать отношение с соответствующими данными отношения в Laravel 5,7 - PullRequest
1 голос
/ 04 марта 2020

Позвольте мне дать вам базовый обзор c:

Существует приложение, в котором люди регистрируют своих питомцев и сообщают, когда животное потеряно. Кроме того, люди, которые видели потерянное домашнее животное, сообщали о его обнаружении, так что владелец домашнего животного был бы уведомлен, и он мог забрать своего домашнего животного.

У меня есть пять моделей: -

Цветовая модель

class Color extends Model
{
    public function colorPet()
    {
        return $this->hasMany('App\Models\Pet');
    }
}

Модель породы

class Breed extends Model
{
    public function breedPetType()
    {
        return $this->belongsTo('App\Models\PetType', 'pet_type_id');
    }

    public function breedPet()
    {
        return $this->hasMany('App\Models\Pet');
    }
}

Модель питомца

class PetType extends Model
{
    public function petTypeBreed()
    {
        return $this->hasMany('App\Models\Breed');
    }
}

Модель питомца

class Pet extends Model
{
    public function petBreed()
    {
        return $this->belongsTo('App\Models\Breed', 'breed_id');
    }

    public function petPetType()
    {
        return $this->belongsTo('App\Models\PetType', 'pet_type_id');
    }

    public function petColor()
    {
        return $this->belongsTo('App\Models\Color', 'color_id');
    }

    public function petUser()
    {
        return $this->belongsTo('App\User', 'user_id');
    }
}

Потерянный отчет

class LostReport extends Model
{
    public function lostReportPet()
    {
        return $this->belongsTo('App\Models\Pet', 'pet_id');
    }

    public function lostReportUser()
    {
        return $this->belongsTo('App\User', 'user_id');
    }

    public function lostReportPetSighting()
    {
        return $this->hasMany('App\Models\PetSighting', 'lost_report_id');
    }
}

Прицел питомца

class PetSighting extends Model
{
    public function petSightingLostReport()
    {
        return $this->belongsTo('App\Models\LostReport', 'lost_report_id');
    }
}

Вот запрос ny: -

$petSightingRadiusQueryString = "( $unitDistance * acos( cos( radians($latitude) ) * cos( radians( pet_sightings.latitude ) ) 
    * cos( radians( pet_sightings.longitude ) - radians($longitude) ) + sin( radians($latitude) ) * sin(radians(pet_sightings.latitude)) ) )";

$lostPetQuery   = LostReport::with('lostReportPet')
                            ->where(array(
                                'lost_reports.is_found' => Globals::SMALL_CHAR_NO))
                            ->whereHas('lostReportPet', function($queryReportPet) {
                                $queryReportPet->where(array(
                                            'pets.status'       => Globals::SMALL_CHAR_ACTIVE,
                                            'pets.is_delete'    => Globals::SMALL_CHAR_NO,
                                            'pets.is_lost'      => Globals::SMALL_CHAR_YES
                                ));
                            });

$lostPetQuery   = $lostPetQuery->where(function($orQuery) use($userId, $petTypeArrayForLostPet, $lostPetRadiusQueryString, $lostPetRadius, $petSightingRadiusQueryString, $petSightingRadius){
                        $orQuery->where('lost_reports.user_id', $userId) // where the post report is by owner
                                ->orWhere(function($lostPetNotificationQuery) use($petTypeArrayForLostPet, $lostPetRadiusQueryString, $lostPetRadius){
                                    $lostPetNotificationQuery->whereIn('pets.pet_type_id', $petTypeArrayForLostPet)
                                                    ->whereRaw($lostPetRadiusQueryString . ' < ' . $lostPetRadius);
                                }) // where the lost report is of same pet type
                                ->orWhereHas('lostReportPetSighting', function($petSightingNotificationQuery) use ($petSightingRadiusQueryString, $petSightingRadius){
                                    $petSightingNotificationQuery->whereRaw("pet_sightings.id = (SELECT MAX(pet_sightings.id) FROM pet_sightings WHERE pet_sightings.lost_report_id = lost_reports.id) AND " .  $petSightingRadiusQueryString . " < " . $petSightingRadius);
                                }); // where pet sighting is enabled
                    });

Вот результат, который я получаю: -

Array
(
    [id] => 1
    [pet_id] => 3
    [user_id] => 2
    [phone] => 6290453837
    [latitude] => 22.572645
    [longitude] => 88.363892
    [missing_date] => 2020-03-03 00:00:00
    [found_date] => 
    [is_found] => n
    [is_delete] => n
    [created_date] => 2020-03-03 15:08:03
    [modified_date] => 2020-03-03 15:08:03
    [created_at] => 2020-03-03 15:08:03
    [updated_at] => 2020-03-03 15:08:03
    [lost_report_pet] => Array
        (
            [id] => 3
            [name] => Micky
            [image] => p-1583228283-3.jpg
            [pet_type_id] => 1
            [breed_id] => 1
            [color_id] => 1
            [age] => 2
            [weight] => 7
            [description] => Very cute doggo
            [is_approachable] => y
            [user_id] => 2
            [status] => a
            [is_delete] => n
            [is_lost] => y
            [created_date] => 2020-03-03 15:08:03
            [modified_date] => 2020-03-03 15:08:03
            [created_at] => 2020-03-03 15:08:03
            [updated_at] => 2020-03-03 15:08:03
        )

)

Как видите, отношение 'lost_report_pet'. Как я могу получить отношение породы, окраса и питомца от lost_report_pet?

1 Ответ

2 голосов
/ 04 марта 2020

Я почти уверен, что вы можете попробовать использовать обозначение точки отношения:

LostReport::with([
    'lostReportPet.petBreed', 
    'lostReportPet.petPetType',
    'lostReportPet.petColor'
]);
...