2017-05-10 41 views
1

因此,我很难取回多态关系的所有者。这很简单。完全按照文档所述。我已经能够取得孩子,但不是所有者。在Laravel 5.4中获取多态关系的所有者

这是我的表结构:

histories table structure

表结构,库存表:

Structure for inventory table

历史模式:

namespace App; 

use Illuminate\Database\Eloquent\Model; 
use Illuminate\Database\Eloquent\Relations\Relation; 

Relation::morphMap([ 
    'inventory' => 'App\Inventory', 
    'customer' => 'App\Customer', 
    'supplier' => 'App\Supplier', 
]); 

class History extends Model 
{ 
    public function product() 
    { 
    return $this->belongsTo('App\Product'); 
    } 

    public function moveTo() 
    { 
    return $this->morphTo(); 
    } 
} 

这是库存模型:

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class Inventory extends Model 
{ 
    public function users(){ 
    return $this->belongsToMany('App\User'); 
    } 

    public function products(){ 
    return $this->hasMany('App\Product'); 
    } 

    public function histories() 
    { 
    return $this->morphMany('App\History', 'moveTo'); 
    } 
} 

不幸的是,dd($history->moveTo);返回的null值。

但是,如果我做dd($inventory->histories);,所有的数据都在那里。

任何人有任何想法为什么?

回答

0

您正在定义库存模型中的morphMap,但它需要在服务提供商中定义。您可以构建自己的服务提供商或将其置于AppServiceProvider的引导方法中。

class AppServiceProvider extends ServiceProvider 
{ 
    public function boot() 
    { 
     Relation::morphMap([ 
      'inventory' => 'App\Inventory', 
      'customer' => 'App\Customer', 
      'supplier' => 'App\Supplier', 
     ]); 
    } 
} 
+0

试过了。仍然返回'null'。 – kamudrikah

+0

但它仍然是一个很好的做法,即使它没有修复,也可以通过使用'ServiceProvider'来实现:) –

1

你必须包括这里面的关系$this->morphTo('moveTo');以及

public function moveTo() 
{ 
    return $this->morphTo('moveTo'); 
} 

我不知道,但Laravel变身关系使用able作为后缀例如commentabletaggable。这样你就不必在上面做。

这解决了我的问题。希望能帮助到你。 :)

+0

这个答案对你有帮助吗? –