拉拉维尔在哪里搜索查询



我有一个空格和一个兴趣表。

我目前能够获取另存为$spaceList的空间 ID 列表,但我希望我的 $query 变量检索space_id外键与我的$spaceList变量中的space_id之一匹配的兴趣列表。

public function index() {
        $user_id = auth()->user()->id;
        $user = User::find($user_id);
        $spaceList = Space::where('user_id', $user_id)->pluck('space_id')->toArray();
        $query = Interest::where('space_id', $spaceList);
        $interests = $query->get(); 
        return view('dashboard')->with('space', $user->space)->with('interest', $interests);
}

谢谢,我已经在这里工作了很长时间了。

你应该使用whereIn而不是where

$spaceList = Space::where('user_id', $user_id)->pluck('space_id')->toArray();
$query = Interest::whereIn('space_id', $spaceList);

在 Laravel Eloquent 中,这就是查询关系存在所处理的内容

如果 $spaceList 变量未在其他地方使用,则此处不需要该变量

$query = Interest::whereHas('spaces', function($query) use ($user_id) {
    $query->where('user_id', '=', $user_id);
});

请注意,要获得这项工作,您需要在兴趣模块中声明空格一对多关系

应该是这样的,更多详细信息请参阅此处的文档

namespace App;
use IlluminateDatabaseEloquentModel;
class Interest extends Model
{
    public function spaces()
    {
        // space_id is the column name in your space database table
        // id the the foreign-key target, generally is the primary-key of space table
        return $this->hasMany('AppSpace', 'space_id', 'id');
    }
}

最新更新