【问题标题】:How to get model through many-to-many relationship in Laravel如何通过 Laravel 中的多对多关系获取模型
【发布时间】:2020-02-20 06:56:39
【问题描述】:

我在 Laravel 中遇到过如下情况,简单可视化如下:

task -([many-to-many]- task_user -[many-to-many])- user -[one-to-one]- info

我能够从任务到用户,但不幸的是我无法获取信息。

有人知道我错过了什么吗?

模型:任务

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Task extends Model
{

    public $table = "tasks";
    public function taskuser(){
         //task->task_user->user->info
        return $this->belongsToMany(User::class,'task_user');
}

当我将 ->belongsTo(Info::class) 添加到函数 taskuser 时,我收到以下错误:

Illuminate\Database\Eloquent\RelationNotFoundException
Call to undefined relationship [taskuser] on model [App\Models\Task].

我肯定错过了什么,但是什么?

编辑:信息模型与用户一起使用用户->信息给出正确的结果 模型用户:

public function info()
{
    return $this->hasOne('App\Models\Info');
}

编辑:控制器

$task= Task::whereBetween('datetime',array($start,$end))->with('tasktype','taskuser')->get();

编辑:相关表格

    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('username');
        $table->rememberToken();
        $table->timestamps();

    Schema::create('infos', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned(); //internal id
        $table->string('name');  
        #foreign references
        $table->foreign('user_id')->references('id')->on('users');  

    Schema::create('tasks', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('task_types_id')->unsigned();  
        $table->string('title');  
        $table->datetime('datetime');  
        $table->integer('length'); 
        $table->string('description')->nullable(); 
        $table->integer('updated_by')->unsigned(); 
        $table->timestamps();
        #foreign references
        $table->foreign('task_types_id')->references('id')->on('task_types');
        $table->foreign('updated_by')->references('id')->on('users');           

    Schema::create('task_users', function (Blueprint $table) {
        $table->integer('task_id')->unsigned(); 
        $table->integer('user_id')->unsigned(); 
        #foreign references
        $table->foreign('task_id')->references('id')->on('tasks');
        $table->foreign('user_id')->references('id')->on('users');

【问题讨论】:

  • 你能把那个函数的名字taskuser改成mytaskuser并检查同样的错误吗?
  • 错误是一样的。将使用来自控制器的数据进行编辑
  • 你能不能给你看一下表格?
  • 我有一个任务,task_user,用户和信息表
  • 我的意思是你可以实际显示列而不是表名

标签: laravel orm model


【解决方案1】:

通过阅读更多 Laravel 文档,特别是 https://laravel.com/docs/6.x/eloquent-relationships#eager-loading

添加 .info

     $task= Task::whereBetween('datetime',array($start,$end))
     ->with('tasktype','taskuser.info')
     ->get();

现在可以了。

【讨论】:

    猜你喜欢
    • 2013-07-04
    • 1970-01-01
    • 2019-12-22
    • 1970-01-01
    • 1970-01-01
    • 2018-05-20
    • 2020-10-11
    • 2016-12-20
    • 1970-01-01
    相关资源
    最近更新 更多