gpt4 book ai didi

Laravel 4.1 - 基于数据透视表值的 Eloquent 延迟加载和过滤结果

转载 作者:行者123 更新时间:2023-12-01 08:29:37 26 4
gpt4 key购买 nike

我有 2 个模型,SoundTag:

<?php

class Sound extends Eloquent{

protected $table = 'sounds';

protected $guarded = array('id');

public function tags()
{
return $this->belongsToMany('Tag');
}
}

<?php

class Tag extends \Eloquent {

protected $table = 'tags';

protected $guarded = array('id');

public function sounds()
{
return $this->belongsToMany('Sound');
}
}

在 Controller 中我进行延迟加载,它按预期工作; sounds 被提取并且每个都附加了 tags。下面的代码:

$sounds = Sound::with(array('tags'))->get();

我现在想通过 tag_id 过滤 sounds(只获取附加了特定标签的声音),我不确定在 Eloquent 中是否可以.

我尝试了急切的负载约束,但这些只会指定 tag 是否附加到 sound 的条件,而不是实际过滤 声音

我应该改用查询生成器吗?

谢谢。

最佳答案

试试这个代码

$sounds = Sound::whereHas('tags', function($q) use($tag_id)
{
$q->where('tags.id', '=', $tag_id);

})->get();

所以你只能得到带有特定标签的声音。

关于Laravel 4.1 - 基于数据透视表值的 Eloquent 延迟加载和过滤结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22598325/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com