Модель отношений Laravel: сделать ее плоской - PullRequest
0 голосов
/ 20 февраля 2019

Пожалуйста, помогите установить связь в модели Laravel.

У меня есть 3 модели, связанные друг с другом.$ Обзор-> inquiry-> продукт.

Как установить связь $ обзор-> продукт?

В запросах есть product_id

class Inquiry extends Model
{
    public function product() {
        return $this->belongsTo(Product::class);
    }
}

В отзывах есть query_id

class Review extends Model
{
    protected $fillable = ['content', 'rating', 'approved'];

    public function inquiry() {
        return $this->belongsTo(Inquiry::class);
    }

    // This code does not work correctly when trying to get collection, it 
    // returns products in order (1, 2, 3, 4, 5), but not related to inquiry
    public function product() {
        $relation = $this->belongsTo(Product::class, 'id');

        // get underlying Query\Builder
        $query = $relation->getQuery()->getQuery();

        // set table to select reviews from
        $query->from = 'reviews';

        // Delete the already built "inner join".
        $query->joins = [];

        // Delete the already built "where".
        $query->wheres = [];

        // Delete all bindings.
        $query->setBindings([]);

        // Create a new inner join with the needed or condition.
        $query->join('inquiries', function($join)
        {
            $join->on('reviews.inquiry_id', '=', 'inquiries.id');
        });

        $query->join('products', function($join)
        {
            $join->on('products.id','=','inquiries.product_id');
        });

        $query->select('products.*');

        return $relation;
    }
}

Мне нужен продуктОтношение Отзывы

1 Ответ

0 голосов
/ 20 февраля 2019

Я нашел решение: github.com/staudenmeir/belongs-to-through

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