【问题标题】:Joining models in eloquent Laravel 5.3在雄辩的 Laravel 5.3 中加入模型
【发布时间】:2017-04-07 01:09:32
【问题描述】:

我是 Laravel 的新手。 这是我的架构:

Schema::create('cluster_info', function (Blueprint $table) {
            $table->increments('id');
            $table->string('code')->unique();
            $table->string('pa_lastname');
            $table->string('pa_firstname');
            $table->string('pa_middlename');
            $table->string('pa_suffix');
            $table->integer('branch_id');
            $table->timestamps();

        });
 Schema::create('cluster_grouping', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('cluster_id');
            $table->integer('client_id');
            $table->timestamps();

        }); 
 Schema::create('branch', function (Blueprint $table) {
            $table->increments('id');
            $table->string('code')->unique();
            $table->string('name');
            $table->string('region');
            $table->timestamps();

        });

我想加入cluster_infobranch。所以在我的Cluster_Info 模型中:

 public function Branches(){
        return $this->hasOne('App\Branch');
    }

当我在我的控件中调用它时,它具有 null

$cluster = new App\Cluster_Info;
dd($cluster->Branches());

【问题讨论】:

  • cluster_info in branch 的外键是什么?
  • 在cluster_info表的分支表中定义外键
  • @BalrajAllam 如何在 clusteri_info 中定义分支表的外键?
  • 使用 php artisan migrate:rollback 回滚迁移,然后在分支架构中添加 $table->integer('cluster_info_id') $table->foreign('cluster_info_id')->references('id')->on('cluster_info')

标签: php laravel laravel-5 model eloquent


【解决方案1】:

请阅读here,了解什么是外键以及如何在表中写入外键。请参阅 laravel 的命名约定讨论here

如果您正确添加了表名和外键,那么您的关系应该可以正常工作。否则,您可以使用以下方法并将外键作为第二个参数传递。阅读One to One Relationship的详细信息

return $this->hasOne('App\Branch', 'foreign_key');

【讨论】:

    【解决方案2】:

    检查您的本地和外键:

    return $this->hasOne('App\Branch', 'id', 'cluster_id');
    

    这可能是您在控制器中编写的方式,因为为了存在关系,应该在现有的 Cluster_Info 实例上请求关系方法,如下所示:

    $clusters = Cluster_Info::all();
    foreach($clusters as $clusterInfo) {
      dump($clusterInfo->Branches());
    }
    

    或者使用eager loading:

    $clusters = Cluster_Info::with('Branches')->get();
    

    还要确保 Eloquent 知道您的表名,因为我不确定您是否符合 Laravel 的约定。

    class Cluster_Info {
      protected $table = 'cluster_info';
    }
    

    为了可读性,我建议使用branch() 之类的方法而不是Branches(),因为它应该只返回一个结果。也看看Eloquent model conventions,他们可以让你的生活更轻松。

    【讨论】:

    • 我尝试过预先加载,这是结果列未找到:1054 Unknown column 'branch.cluster__information_id' in 'where Clause' (SQL: select * from branch where branch.@987654332 @ in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 , 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49 , 50, 51, 52, 53, 54, 64, 67))
    猜你喜欢
    • 2017-02-16
    • 1970-01-01
    • 2021-08-11
    • 2017-07-01
    • 2017-05-19
    • 1970-01-01
    • 2017-04-28
    • 2018-10-11
    • 2015-08-15
    相关资源
    最近更新 更多