【问题标题】:Laravel Relationships / attributes to common linked tableLaravel 关系/属性到公共链接表
【发布时间】:2018-12-28 09:39:52
【问题描述】:

让我先说我对 Laravel 非常陌生。 我有一个列表框项目表(下面截断的迁移代码):

$table->increments('id');
$table->string('list_item');
$table->string('group');
$table->integer('sort_order')->default(1);

组用于例如“TITLE”、“SPECIALITIES”等。 我将 user_title_li_id (在 users 表中)链接到该表的 id,以及 provider_title_li_id,provider_speciality_li_id 在providers表等

如何在 User 和 List Item 模型中建立关系,以便为控制器中的每个模型获取 list_item(例如教授)?

【问题讨论】:

  • 这不是migration吗?不是模型.. 顺便说一句,不要忘记添加the foreign key constraint。之后add a relation on the model。哦,对了,laravel 也有默认的命名约定,可以方便地帮助框架找到关系。
  • "(下面截断的 MIGRATION 代码)" 那么我猜我是否将 FK 约束添加到两个表中?
  • 如果我需要在迁移中添加 FK,它需要看起来像这样:$table->increments('id')->unsigned(); $table->foreign('id')->references('user_title_li_id')->on('users'); $table->foreign('id')->references('provider_title_li_id')->on('providers'); $table->foreign('id')->references('provider_speciality_li_id')->on('providers'); ....我不确定这是否允许?

标签: php laravel models controllers relationships


【解决方案1】:

在您的用户模型中,定义如下函数:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Get the list items for the user.
     */
    public function listItems()
    {
        return $this->hasMany('App\ListItem', 'foreign_key', 'list_item');
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-17
    • 2021-03-11
    • 1970-01-01
    • 2014-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多