Есть ли способ указать столбец целевого идентификатора в методе morphTo?
Я приведу пример, который есть в документации для laravel:
Пост - идентификатор, текст
Видео — идентификатор, URL
Комментарий — идентификатор, текст, commentable_id, commentable_type
Но что, если идентификаторы поста и видео были переименованы в custom_id? Как бы я тогда настроил свою красноречивую модель? Спасибо.
Изменить:
Я до сих пор не понимаю, вот полный код:
Структура таблицы:
comments - id, text, commentable_id, commentable_type, user_id
posts - custom_id, text
videos - custom_id, url
users - id, name, email, password,...
Модель комментария:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function commentable()
{
return $this->morphTo();
}
}
Видео модель:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Video extends Model
{
public function comments()
{
return $this->morphMany('App\Comment', 'commentable', 'commentable_type', 'commentable_id', 'custom_id');
}
}
Почтовая модель:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function comments()
{
return $this->morphMany('App\Comment', 'commentable', 'commentable_type', 'commentable_id', 'custom_id');
}
}
Пользовательская модель:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function comments()
{
return $this->hasMany('App\Comment');
}
}
ТестКонтроллер:
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
class TestController extends Controller
{
public function test()
{
$user = User::first();
$comments = $user -> comments;
foreach ($comments as $comment)
{
return $comment -> commentable;
}
}
}
И он по-прежнему выдает исключение запроса Неизвестный столбец posts.id
Пожалуйста, объясни. Спасибо.