hteen
V2EX  ›  问与答

laravel where 查询问题, 字符串被转为 int 了

  •  
  •   hteen · Dec 19, 2019 · 2356 views
    This topic created in 2513 days ago, the information mentioned may be changed or developed.

    模型写法

    User::where('foo', 10)->first();
    

    执行的 sql 语句

    select * from `users` where `foo` = 10
    

    foo 字段其实是个 varchar

    User::where('foo', '10')->first();
    

    执行的 sql 语句, 参数还是被转为 int 了

    select * from `users` where `foo` = 10
    

    如果传递其他字符串

    User::where('foo', 'abc')->first();
    

    执行的 sql 语句, 参数就是期望值

    select * from `users` where `foo` = 'abc'
    

    laravel5.8

    5 replies  •  2019-12-19 19:57:56 +08:00
    iyaozhen
    iyaozhen
    Dec 19, 2019 via Android
    1
    MySQL 里面试过吗?我记得不区分 10 还是'10'
    hteen
    hteen
    OP
    Dec 19, 2019
    2
    @iyaozhen 分析 SQL 语句, 10 是用不到索引的, '10'才能命中索引
    ylsc633
    ylsc633
    Dec 19, 2019
    3
    恭喜你 遇到了一个 建立索引,且用了索引字段,但不走索引的情况!

    以后可能会被问到! 哈哈哈
    chinvo
    chinvo
    Dec 19, 2019 via iPhone
    4
    我记得 laravel 的 ORM 有个强制类型的参数,太就没用过有点记不清
    zibber
    zibber
    Dec 19, 2019
    5
    User::where('foo', Db:raw("'10'"))->first();
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1525 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 23:06 · PVG 07:06 · LAX 15:06 · JFK 18:06
    ♥ Do have faith in what you're doing.