无法将用户名添加到帖子作者

时间:2018-12-24 04:34:43

标签: php laravel eloquent backpack-for-laravel

我正在尝试将用户表中作者的用户名插入posts表中,但我没有这么做。我在为CRUD使用背包,但不确定自己在做什么错。我也不确定为什么会显示用户名而不是用户名本身的ID,因为正确的用户名会出现在选择框中。我收到以下错误:

  

SQLSTATE [23000]:违反完整性约束:1452无法添加或   更新子行:外键约束失败(idfposts,   约束posts_author_foreign外键(author)参考   usersusername))(SQL:插入poststitlecontent,   authorupdated_atcreated_at)值(aasdasd,

asdasda

,   1,2018-12-24 04:25:23,2018-12-24 04:25:23))

我正在运行SQL 8,Laravel 5.7和PHP 7.1.19。到目前为止,我已经尝试通过artisan命令清除缓存并执行migration:refresh(这很好,因为我没有合法数据)。

  

在App \ Models \ Post中:

protected $table = 'posts';
protected $primaryKey = 'id';
protected $foreignKey = 'author';
public $timestamps = true;
protected $guarded = ['id'];
protected $fillable = [
    'title', 'content', 'author'
];
protected $hidden = [];
protected $dates = [];

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

帖子表创建:

Schema::create('posts', function (Blueprint $table) {
        $table->increments('id')->unique();
        $table->string('title')->required();
        $table->longtext('content')->required();
        $table->string('author');
        $table->foreign('author')->references('username')->on('users');
        $table->timestamps();
    });

在PostCrudController上选择框:

$this->crud->addField([
        'label' => "Author",
        'type' => 'select2',
        'name' => 'author', // the db column for the foreign key
        'entity' => 'user', // the method that defines the relationship in your Model
        'attribute' => 'username', // foreign key attribute that is shown to user
        'model' => "App\Models\User", // foreign key model
        'options'   => (function ($query) { //limit to only admins
            return $query->orderBy('username', 'ASC')->where('admin', 1)->get();
        }), 
    ]); 

总而言之,我只需要允许将select下拉列表中的用户名插入到author列中,这将是用户本身的用户名。

1 个答案:

答案 0 :(得分:3)

我从您的问题中了解到的是,您正在尝试在posts表和用户之间添加关系。 因此,从我的角度来看,不要像

$table->foreign('author')->references('username')->on('users');

您应该像这样进行外键

$table->unsignedInteger('user_id')
$table->foreign('user_id')
    ->references('id')
    ->on('users')
    ->onUpdate('CASCADE')
    ->onDelete('CASCADE');

然后您可以在user_id列中传递用户的ID,以建立两者之间的关系。

使用这样的外键的好处是 id列是users表中的主键,因此它将唯一地标识您的用户 并且它是一个无符号整数,因此SQL引擎很容易为此索引。

现在要分配数据,您肯定可以在Post模型中建立以下雄辩的关系

public function user() {
    return $this->belongsTo('App/User');
}

在添加帖子时,您可以使用

之类的急切加载(with()雄辩的方法)
$posts = Post:::with('user)->get();

现在有了所有帖子,您可以访问任何关联的用户信息,例如:

forach ($posts as $post){
    $userName = $post->user->name;
}

希望这会有所帮助。

相关问题