R
R
Ruslan Gillyazanov2018-10-23 00:55:20
MySQL
Ruslan Gillyazanov, 2018-10-23 00:55:20

How to execute a query in Laravel?

What is the correct way to execute such a query using the Laravel query builder?

SELECT * FROM `cards` INNER JOIN `mechanics_field` WHERE `mechanics_field`.`mechanics_id` = 1 AND `cards`.`id` = `mechanics_field`.`card_id` and `cards`.`cost` = 3

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kairat Ubukulov, 2018-10-23
@trycode

First, you have an error in your request. She must be something like this.

SELECT * FROM `cards` 
INNER JOIN `mechanics_field` ON `mechanics_field`.card_id=`cards`.id
WHERE `mechanics_field`.`mechanics_id` = 1 and `cards`.`cost` = 3

And the same query in the Laravel constructor:
$result = DB::table('cards')
  ->join('mechanics_field', 'mechanics_field.mechanics_id', '=', 'cards.mechanic_id')
  ->where(['mechanics_field.mechanics_id' => 1, 'cards.cost' => 3])
  ->get();

And if there is a Card model, then you can write like this:
$result = Card::where(['mechanics_field.mechanics_id' => 1, 'cards.cost' => 3])
      ->select('cards.*')
      ->join('mechanics_field', 'mechanics_field.mechanics_id', '=', 'cards.mechanic_id')
      ->get();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question