dongxian6653 2015-05-01 15:31
浏览 64
已采纳

Laravel在关系对象上的位置

I'm developing a web API with Laravel 5.0 but I'm not sure about a specific query I'm trying to build.

My classes are as follows:

class Event extends Model {

    protected $table = 'events';
    public $timestamps = false;

    public function partecipants()
    {
        return $this->hasMany('App\Partecipant', 'IDEvent', 'ID');
    }

    public function owner()
    {
        return $this->hasOne('App\User', 'ID', 'IDOwner');
    }
}

and

class Partecipant extends Model {

    protected $table = 'partecipants';
    public $timestamps = false;

    public function user()
    {
        return $this->belongTo('App\User', 'IDUser', 'ID');
    }

    public function event()
    {
        return $this->belongTo('App\Event', 'IDEvent', 'ID');
    }
}

Now, I want to get all the events with a specific participant. I tried with:

Event::with('partecipants')->where('IDUser', 1)->get();

but the where condition is applied on the Event and not on its Partecipants. The following gives me an exception:

Partecipant::where('IDUser', 1)->event()->get();

I know that I can write this:

$list = Partecipant::where('IDUser', 1)->get();
for($item in $list) {
   $event = $item->event;
   // ... other code ...
}

but it doesn't seem very efficient to send so many queries to the server.

What is the best way to perform a where through a model relationship using Laravel 5 and Eloquent?

  • 写回答

2条回答 默认 最新

  • duanlu1908 2015-05-01 15:54
    关注

    The correct syntax to do this on your relations is:

    Event::whereHas('partecipants', function ($query) {
        $query->where('IDUser', '=', 1);
    })->get();
    

    Read more at https://laravel.com/docs/5.8/eloquent-relationships#eager-loading

    P.S. It's "participant", not "partecipant".

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)