14

Struggling to write the query with query builder for an hour, gave up and wrote the raw query in 5 minutes.

Comments
  • 1
    But what happens when someone changes the DB backend?
  • 0
    @Nexion In laravel query builder, you can do this:
    DB::select(DB::raw ($query_str));
    So even if you change the db it will not affect as long as the tables are there.
  • 1
    @mohammed not necessarily. If you are using database specific keywords they won't always work. Or will behave differently.
  • 0
    @Nexion Oh I got you now, you meant what if they change the db driver.
    Yes you are right in that case :)
  • 1
    I'd be really intersted to hear what kind of query it was. Maybe you just needed to call a model with a relationship on it. Eloquent will return an object with all needed attributes
  • 0
  • 0
    @mohammed hmmm... Not sure how those tables are related but if they are - why not just grab your model with its relation ->where() the ID is the one you need and just do a ->count() on the collection attribute?

    That would get you all the stuff from the tables you want and you can count / sum whichever attribute you need.
  • 0
    @Skipp The two tables are products and stocks. Stocks has a product id as foreign key referencing id in products table.
    My query is to get each product and their quantity by adding all the stock quantity of that product.
    I will appreciate it, If you can help me with some code example on SO. Thanks :)
  • 1
    @mohammed does your stocks table contain the amount left or do you need to do some counting from a different table? Because if you have the amount set as a column in your stocks table you can just do something like $products = Products::with('stock')->get(); and access the amount with $products->stock->amount

    But to be actually sure, i'd have to see your db layout.

    If you came to laravel from pure php background or any other mvc php framework that uses a query builder (like codeigniter for example) you need some time to understand eloquent. Once you do - it will be a mind-opener :)
  • 0
    @Skipp in my system a product can have multiple stocks from different vendors, so no I don't have the amount left. I have added my table schema in the stack overflow link above, if you could have a look at it when you are free :)
  • 1
    @mohammed sure thing. I'll take a look tomorrow from work. Gonna hit the bed now
  • 1
    Take a look at your SO post and try what I just posted
  • 0
    Works perfectly, thank you very much :)
  • 1
    @mohammed hehe, glad to be if help
Add Comment