【问题标题】:laravel foreign key for string type (null issue)字符串类型的 laravel 外键(空问题)
【发布时间】:2018-04-17 14:19:50
【问题描述】:

我正在尝试从用户表中获取(然后显示)带有外键的文章表中的创建者/作者姓名。我只是 laravel 的新手,希望你能帮我解决这个问题。我对 int 类型的 F-key(s) 没有任何问题,但对于字符串类型,我可能在某处遗漏了一些东西。有时它会给我一些错误,有时一切正常,但文章表上的 user_name 只是保持为空。 如果您需要有关某事的更多信息,请发表评论。 提前致谢!

文章的架构

Schema::create('articles', function (Blueprint $table) {
      $table->engine = 'InnoDB';
      $table->increments('id');
      $table->integer('user_id')->unsigned();
      $table->string('user_name')->nullable();
      $table->string('title');
      $table->text('body');
      $table->timestamps();
      $table->timestamp('published_at');

      $table->foreign('user_id')
            ->references('id')
            ->on('users')
            ->onDelete('cascade');

      $table->foreign('user_name')
            ->references('name')
            ->on('users')
            ->onDelete('cascade');
  });

用户的架构

        Schema::create('users', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->increments('id');
        $table->string('name')->unique();
        $table->string('email')->unique();
        $table->string('password', 60);
        $table->rememberToken();
        $table->timestamps();
    });

【问题讨论】:

标签: php string laravel null key


【解决方案1】:

不要在文章中保存用户名。 您只需保存用户 ID 并在模型中创建关系,如

class User extends Model {
  public function articles() {
    return $this->hasMany('App\Article');
  }
}

class Article extends Model {
  public function user() {
    return $this->belongsTo('App\User');
  }
}

如果您的关系设置正确,您可以像这样访问用户名:

$article->user->name

在另一个方向,您可以为用户撰写文章:

$user->articles

注意:关系的处理方式类似于属性,而不是函数。

【讨论】:

    【解决方案2】:

    我的建议是……

    1. 从文章中删除用户名。让 user_id 指向用户数据。
    2. 使用 laravel 内置的扩展 Model 的 User 类
    3. 创建一个文章类来扩展模型
    4. 设置它们之间的关系

    应用程序/用户.php

    namespace App;
    use Illuminate\Database\Eloquent\Model;
    use ...
    
    class User extends ...{
    
        public function Articles(){
            return $this->hasMany(Articles::class)
        }
    }
    

    App/Article.php 使用 Illuminate\Database\Eloquent\Model;

    namespace App;
    class Article extends Model{
        public function User(){
            return $this->belongsTo(User::class);
        }
        public function getAuthorAttribute(){
            return $this->User->name;
        }
    }
    

    现在您可以访问数据...

    $user->Articles;
    $article->User
    $article->author
    

    要优化访问,您可以通过调用任何关系作为函数来获取查询生成器。

    $user->Articles()->where('title, 'like', 'cars')->get()
    

    看看发生了什么……

    $user->Articles()->where('title, 'like', 'cars')->toSql()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-31
      • 2021-09-14
      • 2019-10-02
      • 2016-12-17
      • 2022-01-06
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多