如何使用 Laravel 5.5 从多态关系中检索数据?

Tha*_*Dao 5 php laravel laravel-5

我是 Laravel 的新手。我正在开发一个演示,Polymorphic Relations遵循文档

我设置了3张表:

--Users
  --id
  --username
--Posts
  --id
  --summary
  --published
--Images
  --id
  --link
  --alt
  --image_id
  --image_type
Run Code Online (Sandbox Code Playgroud)

App\Models\Users

public function scopeWithImages()
{
    return static::with('images')->get();
}

public function images()
{
    return $this->morphMany('App\Models\Images', 'image');
}
Run Code Online (Sandbox Code Playgroud)

App\Models\Posts

public function scopeWithImages()
{
    return static::with('images')->get();
}

public function images()
{
    return $this->morphMany('App\Models\Images', 'image');
}
Run Code Online (Sandbox Code Playgroud)

App\Models\Images

public function scopeWithUsers ()
{
    return static::with('users')->get();
}

public function users()
{
    return $this->morphedByMany('App\Models\Users', 'image');
}

public function posts()
{
    return $this->morphedByMany('App\Models\Posts', 'image');
}
Run Code Online (Sandbox Code Playgroud)

Users我通过调用和建模轻松获得了图像集合Posts
如何从模型中获取用户和帖子集合Images?我收到错误Unknown column 'images.images_id'

Cha*_*ara 4

你的交往方式是错误的,应该是这样的

App\Models\Users

public function image()
{
    return $this->morphMany('App\Models\Images', 'image');
}
Run Code Online (Sandbox Code Playgroud)

App\Models\Posts

public function image()
{
    return $this->morphMany('App\Models\Images', 'image');
}
Run Code Online (Sandbox Code Playgroud)

App\Models\Images

public function image()
{
    return $this->morphTo();
}
Run Code Online (Sandbox Code Playgroud)

方法名称应该是下划线之前的列名称image_id == image()

更喜欢 - https://laravel.com/docs/5.5/eloquent-relationships#polymorphic-relations