如何在Laravel 5.1中更新hasMany关系


How to update hasMany relationship in Laravel 5.1

我对Laravel完全陌生,我实现了Laravel Auth提供的User表,还为用户元数据创建了一个Key Value pare table表。

用户元表由以下代码创建:

use Illuminate'Database'Schema'Blueprint;
use Illuminate'Database'Migrations'Migration;
class UserMeta extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('user_meta', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->char('meta_key', 255);
            $table->longText('meta_value')->nullable();
            $table->timestamps();
            $table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('user_meta');
    }
}

在我的User model中,我有以下方法:

public function meta() {
    return $this->hasMany('App'Models'UserMeta');
}

在我的UserMeta model中,我有以下方法:

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

到目前为止一切都很好。因此,当我注册一个新用户时,我会执行以下操作:

$user = User::create(
    [
        'name'     => $data['name'],
        'email'    => $data['email'],
        'password' => bcrypt( $data['password'] ),
    ]
);
if ( $user ) {
    $telephone_number = new UserMeta;
    $telephone_number->user()->associate($user);
    $telephone_number->meta_key = 'telephone_number';
    $telephone_number->meta_value = $data['telephone_number'];
    $telephone_number->save();
    $company = new UserMeta;
    $company->user()->associate($user);
    $company->meta_key = 'company';
    $company->meta_value = $data['company'];
    $company->save();
    $web_site = new UserMeta;
    $web_site->user()->associate($user);
    $web_site->meta_key = 'web_site';
    $web_site->meta_value = $data['web_site'];
    $web_site->save();
}
return $user;

我想这应该是执行相同操作的更好方法,但我不知道其他方法是什么:(:)

所以,上面的代码对我来说很好,但现在的问题是值更新。在这种情况下,当我更新用户配置文件时,如何更新Meta Data

UserControlerupdate方法中,我执行以下操作:

$user=user::其中('id','=',$id)->first();

$user->name  = $request->input( 'name' );
$user->email = $request->input( 'email' );
$user->password = bcrypt( $request->input( 'password' ) );
$user->save();

我的$request->input();具有以下额外字段,这些字段对应于元值telephone_numberweb_sitecompany

那么,如何更新user_meta表中的元值呢?

循环值

首先,你是对的,你可以循环通过你的创建方法中的三个键:

// Loop through all the meta keys we're looking for
foreach(['telephone_number', 'web_site', 'company'] as $metaKey) {
    $meta = new UserMeta;
    $meta->meta_key = $metaKey;
    $meta->meta_value = array_get($data, $metaKey);
    $meta->save();
}

更新方法:方法一

然后,在你的更新方法

// Loop through all the meta keys we're looking for
foreach(['telephone_number', 'web_site', 'company'] as $metaKey) {
    // Query for the meta model for the user and key
    $meta = $user->meta()->where('meta_key', $metaKey)->firstOrFail();
    $meta->meta_value = array_get($data, $metaKey);
    $meta->save();
}

记下firstOrFail()以结束查询。这只是我的严格要求。如果你想添加一个不存在的元值,那么你可以用替换这行

// Query for the meta model for the user and key, or
// create a new one with that key
$meta = $user->meta()->where('meta_key', $metaKey)
    ->first() ?: new UserMeta(['meta_key' => $metaKey]);

更新方法:方法二

这种方法效率稍高,但更复杂(但也可能教授Eloquent的一个很酷的功能!)。

您可以先加载所有的元键(请参阅懒惰的渴望加载)。

// load the meta relationship
$user->load('meta');
// Loop through all the meta keys we're looking for
foreach(['telephone_number', 'web_site', 'company'] as $metaKey) {
    // Get the first item with a matching key from the loaded relationship
    // Or, create a new meta for this key
    $meta = $user->meta
        ->first(function($item) use ($metaKey) { 
            return $item->meta_key === $metaKey; 
        }) ?: new UserMeta(['meta_key' => $metaKey]);
    $meta->meta_value = array_get($data, $metaKey);
    $meta->save();
}