Home  >  Article  >  Backend Development  >  Questions about related queries with multiple conditions in Laravel?

Questions about related queries with multiple conditions in Laravel?

PHP中文网
PHP中文网Original
2017-03-21 16:18:454490browse

About the related query problem of multiple conditions in Laravel:

table order Order table:

  • idSelf-incremented ID

  • order _id order number

  • paid_date Payment time

table order_product Order product table:

  • id Self-increment ID

  • fk_order_id Order number, foreign key

  • product_name Name

  • product_number Number

  • quantity Quantity

Table Relationship:

order - 1:n - order_product

Requirement:
By Laravel El oquent ORM implements the following native SQL:

select * from order as A inner join order_product as B on A.order_id=B.fk_order_id 
where (A.paid_date between '2016-01-01' and '2016-09-01') and B.product_name like '%Apple iPhone%'

See the manual I have tried several times and tried to do it, but currently only the condition of B.product_name like is implemented through whereHas. When the condition exists in both tables, it really cannot be done.
I hope Laravel seniors can give me some advice, thank you!

PS. Supplement:
Currently, we are doing filtering and retrieval for the list page, and there is a need for paginate.

Solution:

class Order extends Model
{
    public function scopeProducts($query)
    {
        return $query->join('order_product', function($join) {
            $join->on('order.order_id', '=', 'order_product.fk_order_id');
        });
    }
}
Order::products()->where(....);

The above is about the related query problem of multiple conditions in Laravel. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Related articles:

Laravel related query only obtains part of the data of the managed object

laravel related query problem

laravel related query articles and article authors

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn