gpt4 book ai didi

mysql - Laravel 一对多(多态)关系

转载 作者:行者123 更新时间:2023-11-29 05:02:51 24 4
gpt4 key购买 nike

我正在创建一个 Laravel 项目,管理员和执行人员可以在其中拥有客户。

管理模式

public function clients()
{
return $this->morphMany('App\Client', 'executable');
}

客户端.php

public function executable()
{
return $this->morphTo();
}

客户表

public function up()
{
Schema::create('clients', function (Blueprint $table) {
$table->increments('id');
$table->string('name',100);
$table->morphs('executable');
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('clients');
}

在执行 dd()

$data = App\Admin::find(1)->clients()->get();它返回空

Collection {#524 ▼
#items: []
}

最佳答案

能否请您粘贴更多您的代码信息?

尤其是您如何播种您的管理员客户记录。

下面适合我。

public function testRun()
{
Artisan::call('migrate');

$admin = new Admin();
$admin->id = 1;
$admin->save();

$client = new Client();
$client->id = 11;
$client->name = 'name';
$client->executable_id = 1;
$client->executable_type = 'App\Admin';
$client->save();

dd(Admin::find(1)->clients()->get());
}

结果

Illuminate\Database\Eloquent\Collection {#899
#items: array:1 [
0 => App\Client {#900
#connection: "sqlite"
#table: "clients"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:6 [
"id" => "11"
"name" => "name"
"executable_type" => "App\Admin"
"executable_id" => "1"
"created_at" => "2019-02-16 16:48:59"
"updated_at" => "2019-02-16 16:48:59"
]
...

关于mysql - Laravel 一对多(多态)关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54724865/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com