PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, April 19, 2022

[FIXED] How to Make Laravel Eloquent "AND" in a Query?

 April 19, 2022     eloquent, laravel, mysql, php     No comments   

Issue

I am making a website in my job and I have an issue.

This is what I want to do; in MySQL (PHPMyAdmin) it works with no problems:

SELECT *
FROM tipo_usuarios
INNER JOIN users
    ON tipo_usuarios.id = users.id AND 
       tipo_usuarios.jerarquia = "Administrador";

PHPMyAdmin successful query run

Well this is my Eloquent in Laravel, it works but only with IDs. I don't know how to add AND in Eloquent.

$visitas = User::join("visitas", "visitas.id_usuario", "=", "users.id")
    ->select("*")
    ->get();

code


Solution

You can use function for second argument in join

$visitas = User::join("visitas", function ($join) {
    $join->on("visitas.id_usuario", "=", "users.id")
        ->on("visitas.jerarquia","=","Administrador")
})
    ->select("*")
    ->get();

However, you should read the documentation for creating Eloquent relationship. This is a more convenient and understandable functionality than using the query builder

Eloquent relationship



Answered By - Liudmila Savateeva
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing