【问题标题】:Laravel one to many (polymorphic) relationshipLaravel 一对多(多态)关系
【发布时间】:2019-02-16 15:51:01
【问题描述】:

我正在创建一个 Laravel 项目,其中 Admins & Executives 可以拥有客户。

管理模式

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: []
}

【问题讨论】:

    标签: mysql laravel eloquent


    【解决方案1】:

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

    尤其是您如何播种 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"
          ]
          ...
    

    【讨论】:

    • 非常感谢! @Kit Loong,它奏效了!问题是$client->executable_type = 'App\Admin';
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2016-01-26
      • 1970-01-01
      • 2017-02-28
      • 1970-01-01
      • 1970-01-01
      • 2018-06-15
      • 2017-12-24
      • 2018-03-16
      • 2015-09-14
      相关资源
      最近更新 更多