dota220141003
2018-09-11 05:13
浏览 220
已采纳

如何查询Laravel Eloquent belongsTo关系?

I am studying the Laravel Eloquent Relationships, with different examples. I have a State model and City model, where City belongsTo State and State hasMany City.

As per given code on https://laravel.com/docs/5.7/eloquent-relationships#eager-loading, I successfully queried the states which have cities whose name starts with 'p'. But I am unable to retrieve all those cities whose state names start with 'l'.

This could be a very basic question, but still, I am seeking for help for what goes unsuccessful and why.

图片转代码服务由CSDN问答提供 功能建议

我正在研究Laravel Eloquent Relationships,其中有不同的例子。 我有一个州模型和城市模型,其中城市 属于 州和州 hasMany 城市。

根据 https上的给定代码: //laravel.com/docs/5.7/eloquent-relationships#eager-loading ,我成功查询了名称以'p'开头的城市。 但我无法检索所有那些州名以'l'开头的城市。

这可能是一个非常基本的问题,但我仍在寻求帮助以解决失败的问题。 为什么。

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doupingpeng7567 2018-09-11 05:16
    已采纳

    Try this:

    State::where('name','like','l%')->get();
    

    For querying relationship:

    $states= City::whereHas('state', function ($query) {
       $query->where('name', 'like', 'l%');
    })->get();
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dongtu4559 2018-09-11 05:17

    You could use whereHas to apply filter on related models like

    $states= City::whereHas('state', function ($query) {
        $query->where('name', 'like', 'i%');
    })->get();
    

    Querying Relationship Existence

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题