A
A
Artem2021-06-06 21:47:23
Laravel
Artem, 2021-06-06 21:47:23

How to properly get items from today's DB in Laravel 8?

Good afternoon, I need to get the elements from the database for today using Carbon.
There are 3 tables: districts, addresses, orders. Here are their models:

class Districts extends Model
{
    use HasFactory;
    protected $primaryKey = 'id';
    protected $guarded = [];

    public function address()
    {
        return $this->hasMany('App\Models\Addresses', 'district_id', 'id');
    }
}

class Addresses extends Model
{
    use HasFactory;

    protected $guarded = [];

    public function orders()
    {
        return $this->hasMany('App\Models\Orders', 'address_id', 'id');
    }

    public function district()
    {
        return $this->belongsTo('App\Models\Districts', 'district_id', 'id');
    }
}

class Orders extends Model
{
    use HasFactory;

    protected $guarded = [];

    protected $searchable = [
        'name',
    ];

    public function address()
    {
        return $this->belongsTo('App\Models\Addresses', 'address_id', 'id');
    }
}

The Orders table has a column $table->date('date_of_completion'); which displays on what date the order was created. I need to get all districts where orders date_of_completion will be equal to today.
And this is one of my attempts to get:
$districts = Districts::where(function($ds)
        {
            $ds->address->where(function ($addr)
            {
                $addr->orders->whereDate('date_of_completion', Carbon::today());
            });
        })->get();

To clarify: You need to get all Orders that have Addresses that have Orders that have the date_of_completion field must be equal to today.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin B., 2021-06-06
@artem_atlas

Fuck. Doc teach first. OOP. Turn on your brain, and then spank your shit code.
All of this is spelled wrong. First, learn how to write queries correctly. Then you'll figure out the date

$districts = Districts::where(function($ds) {
            $ds->address->where(function ($addr)
            {
                $addr->orders->whereDate('date_of_completion', Carbon::today());
            });
        })->get();

Hint instead of where use whereHas

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question