模型中的Laravel关系:使其平坦

时间:2019-02-20 05:53:57

标签: laravel eloquent

请帮助在Laravel模型中建立关系。

我有3个彼此相关的模型。 $ review->咨询->产品。

如何建立$ review-> product关系?

查询中有product_id

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

评论包含question_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 :(得分:0)

我找到了解决方案:github.com/staudenmeir/belongs-to-through