Is there a way to specify target id column on morphTo method?
I'll give an example which is in documentation for laravel:
Post - Id, text
Video - Id, url
Comment - Id, text, commentable_id, commentable_type
But what if Ids on post and video were renamed to custom_id? How would I set up my eloquent model then? Thanks.
Edit:
I still don't get it here is the complete code:
Table structure:
comments - id, text, commentable_id, commentable_type, user_id
posts - custom_id, text
videos - custom_id, url
users - id, name, email, password,...
Comment model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function commentable()
{
return $this->morphTo();
}
}
Video model:
<?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');
}
}
Post model:
<?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');
}
}
User model:
<?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');
}
}
TestController:
<?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;
}
}
}
And it still throws query exception Unknown column posts.id
Please explain. Thanks.
via M. Novotny