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

Questions about related queries with multiple conditions in Laravel?

PHP中文网
Release: 2023-03-01 08:00:01
Original
4536 people have browsed it

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
Copy after login

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%'
Copy after login

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');
        });
    }
}
Copy after login
Order::products()->where(....);
Copy after login

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

Related labels:
source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template