Laravel一对多(多态)关系

时间:2019-02-16 15:51:01

标签: mysql laravel eloquent

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

管理员模型

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

Client.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(); 返回null

Collection {#524 ▼
  #items: []
}

2 个答案:

答案 0 :(得分:2)

请粘贴更多代码信息吗?

特别是如何记录adminsclients记录。

以下为我工作。

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"
      ]
      ...

答案 1 :(得分:1)

一旦定义了数据库表和模型,就可以通过模型访问这些关系。例如,要访问clients的所有Admin,可以使用clients动态属性:

$data = App\Admin::find(1)->clients;