Laravel 与 WHERE 子句的关系 returns 无
Laravel Relationship with WHERE clause returns nothing
I have areas
. Each area
have N curses
So, each curse
belongsTo only one area
.
我的class
class Area extends Model
{
public function curses()
{
return $this->hasMany('App\Curse');
}
}
我的控制器
public function getCursesByAreaId()
{
$areaId = Input::get('areaId'); //ID of selected Area
//area_id is a field of table CURSE. A FK to Area.
$areas = Area::with('curses')->where('area_id', $areaId)->get();
foreach($areas as $area)
{
var_dump($areas);
}
}
诅咒模型
class Curseextends Model
{
protected $fillable =
[
'description',
'area_id'
];
}
使用 laravel 的调试栏,我看到正在执行的查询是这样的:
select * from "areas" where "area_id" = '2'
它不是应该 运行 关系查询吗? (有联接)
已经检查过我是否收到了正确的id
,没问题。
问题是它根本没有带来任何数据。
您需要如下内容:
$areas = Area::whereHas('curses', function($query) use ($areaId) {
$query->where('area_id', $areaId);
})
->with('curses')
->get();
仅当您想获得具有匹配诅咒的区域时才需要whereHas
。
但是,如果你只需要相关的诅咒,我认为你可以这样做,因为一个诅咒只属于一个区域,所以,如果有该区域,那么你将获得附加到它的所有诅咒:
$area = Area::with('curses')->find($areaId); // Single area
// Access the curses
$curses = $area->curses; // collection of curses
我认为您正在使用 curse
table 中存在的关系 area_id
,请尝试通过 id
而不是 area_id
检索区域 ID ,像这样:
$areas = Area::where('id', $areaId)->with('curses')->get();
希望您能找到解决方案。
试试这个:
$areas = Area::whereHas('curses', function($area_query) use ($area_id) {
$area_query->where('area_id', $area_id)
})
->with('curses')
->get();
I have
areas
. Eacharea
haveN curses
So, eachcurse
belongsTo onlyone area
.
我的class
class Area extends Model
{
public function curses()
{
return $this->hasMany('App\Curse');
}
}
我的控制器
public function getCursesByAreaId()
{
$areaId = Input::get('areaId'); //ID of selected Area
//area_id is a field of table CURSE. A FK to Area.
$areas = Area::with('curses')->where('area_id', $areaId)->get();
foreach($areas as $area)
{
var_dump($areas);
}
}
诅咒模型
class Curseextends Model
{
protected $fillable =
[
'description',
'area_id'
];
}
使用 laravel 的调试栏,我看到正在执行的查询是这样的:
select * from "areas" where "area_id" = '2'
它不是应该 运行 关系查询吗? (有联接)
已经检查过我是否收到了正确的id
,没问题。
问题是它根本没有带来任何数据。
您需要如下内容:
$areas = Area::whereHas('curses', function($query) use ($areaId) {
$query->where('area_id', $areaId);
})
->with('curses')
->get();
仅当您想获得具有匹配诅咒的区域时才需要whereHas
。
但是,如果你只需要相关的诅咒,我认为你可以这样做,因为一个诅咒只属于一个区域,所以,如果有该区域,那么你将获得附加到它的所有诅咒:
$area = Area::with('curses')->find($areaId); // Single area
// Access the curses
$curses = $area->curses; // collection of curses
我认为您正在使用 curse
table 中存在的关系 area_id
,请尝试通过 id
而不是 area_id
检索区域 ID ,像这样:
$areas = Area::where('id', $areaId)->with('curses')->get();
希望您能找到解决方案。
试试这个:
$areas = Area::whereHas('curses', function($area_query) use ($area_id) {
$area_query->where('area_id', $area_id)
})
->with('curses')
->get();