mysql - Laravel 一对多(多态)关系
问题描述
我正在创建一个 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: []
}
解决方案
您能粘贴更多代码信息吗?
尤其是你如何播种admins
和clients
记录。
下面对我有用。
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"
]
...
推荐阅读
- python - 使用 for 循环变量命名文件
- c# - C# JSON 如何读取具有未知父名的特定值
- azure - Azure Logic App 和 Function App 性能差异
- swift - 滚动时显示重复数据的 CollectionView 单元格?
- android - 当我使用 fragmentTransaction.add 方法时片段重叠
- java - Java+Spark wordCount 与 EMR
- ruby-on-rails - 如何通过 Grape API 在 Rails 中发送 zip 文件
- python - 如何将 AWS 网络负载均衡器与自定义 python 服务器一起使用
- python - 使用python为多个json主体发布请求
- python - TypeError:并非所有参数都在 tkinter 中的字符串格式化期间转换