簡體   English   中英

我如何與多對多關系播種?

[英]How can I seed with many to many relations?

我有一個餐廳應用程序,我在其中為我的餐廳(用戶)和美食類型(類型)創建了播種機。 由於這兩個表具有多對多關系,因此我有一個名為 type_user 的 pivot 表。

但是當我運行播種機時,這張桌子並沒有播種。 如何使用用戶表和類型表中的 id 在我的 UserSeeder 中為 pivot 表 type_user 播種?

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use App\User;
use App\Type;

class UsersSeeder extends Seeder
{
/**
 * Run the database seeds.
 *
 * @return void
 */
public function run()
{
    $users = config('restaurants');

    foreach ($users as $user) {
        $new = new User();

        $new->name = $user['name'];
        $new->slug = Str::slug($user['name'], '-');
        $new->email = $user['email'];
        $new->password = Hash::make($user['password']);
        $new->address = $user['address'];
        $new->vat_number = $user['vat_number'];

        $new->types()->attach($user->id);

        if (array_key_exists('thumb', $user)) {
            $new->thumb = $user['thumb'];
        } else {
            $new->thumb = 'users_thumbs/food_placeholder.jpg';
        }
        $new->save();
    }
}

保存后嘗試附加,您需要具有要與user附加的type_id

$user = $new->save();

$user->type()->attach($type_id)

還要確保您已經在模型中設置了關系。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM