我有三张桌子 user, specialities & results

结果包含specialitie_id, user_id

我创建了多对多关系

下面是用户模型中的关系

public function specialities()
    {
        return $this->belongsToMany(Speciality::class, 'results', 'user_id', 'specialitie_id')->withPivot('result', 'color');
    }

我想从结果表中提取基于specialitie_id的数据

如果我的URL是 abc.com/result/5

I have attached table structure as well, enter image description here

它应该向我显示与specialitie_id 5相关的结果 我试过了,但不起作用

$result = User::with('specialities')->where('id', 5)->get();

任何帮助都将不胜感激.

推荐答案

Your current query:

$result = User::with('specialities')->where('id', 5)->get();

是说,给我所有的结果,其中USER_ID=5WITH,所有与之相关的专业.


You are very close but did it backwards:

//Give me all results where the SPECIALITY_ID = 5 
//WITH all the users related to it
$result = Speciality::with('users')->where('id', 5)->get(); 

Please note that the above is an array

Example of a Controller Function:

public function results($id){
    $results = Speciality::with('users')->where('id', $id)->get(); 

    return view('user_specialities', compact('results'));
}

Example view user_specialities:

@foreach($results as $result)
    <p>Result: {{$result->result}}</p>
    <p>Formulary: {{$result->formulary}}</p>
    <p>Color: {{$result->color}}</p>
    <p>User ID: {{$result->user->id}}</p>
    <p>User Name: {{$result->user->name}}</p>
@endforeach

Speciality Model:

public function users()
{
    return $this->belongsToMany(User::class, 'results', 'specialitie_id', 'user_id')->withPivot('result', 'color');
}

User Model:

public function specialities()
{
    return $this->belongsToMany(Speciality::class, 'results', 'user_id', 'specialitie_id')->withPivot('result', 'color');
}

Laravel相关问答推荐

Laravel复选框值更新

Laravel中如何动态更改路由链接?

Vue 组件中的图像不适用于 Vite + Laravel

Laravel 语法 GroupBy 获取列到数组

为什么使用 created_at 表在迁移错误中创建表?

如何在 Laravel Eloquent Collection 数组之前添加一个键值对?

Laravel - 排序的集合输出不是数组

Laravel 5.x 中 onUpdate / onDelete 的可用操作

Laravel - 超过 PHP 最大上传大小限制时验证文件大小

使用数据库中的值进行动态邮件配置 [Laravel]

如何在 AWS Elastic Beanstalk 上设置和使用 Laravel 调度?

在 php Laravel 5 中创建自定义帮助函数的最佳实践是什么?

如何在 Laravel 5.1 中为Electron邮件添加标题

Composer 致命错误:声明 Fxp... 必须与第 334 行的 ...AbstractAssetsRepository.php 兼容

使用 Laravel 创建新项目会引发异常

在 Laravel 5 控制器中找不到类App\Http\Controllers\DB

找不到框laravel/homestead

Laravel 应用程序连接数据库时速度很慢

Eloquent的 attach/detach/sync 触发任何事件?

如果在 Laravel 5.1 中找不到路由,则显示 404 页面