我与一个亚科有一个简单的关系,该亚科有很多属,每个亚科都有很多种。
所以:
物种通过属有一个亚科。 亚科有很多属。
class Species extends Model
{
/** Return the many-to-one relationship with the Genus model.
*
* @return App\Models\Genus
*/
public function genus()
{
return $this->belongsTo(Genus::class);
}
/** Return the one-to-one relationship with the Subfamily model through the Genus model.
*
* @return App\Models\Subfamily
*/
public function subfamily()
{
return $this->hasOneThrough(Subfamily::class, Genus::class);
}
}
class Genus extends Model
{
/** Returns the one-to-many relationship with the Species class
*
* @return App\Models\Species
*/
public function species()
{
return $this->hasMany(Species::class);
}
/** Returns the many-to-one relationship with the Subfamily class
*
* @return App\Models\Subfamily
*/
public function subfamily()
{
return $this->belongsTo(Subfamily::class);
}
}
class Subfamily extends Model
{
/** Returns the one-to-many relationship with the Genus class
*
* @return App\Models\Genus
*/
public function genera()
{
return $this->hasMany(Genus::class);
}
/** Returns the one-to-many relationship with the Species class through the Genus class
*
* @return App\Models\Genus
*/
public function species()
{
return $this->hasManyThrough(Species::class, Genus::class);
}
}
尝试一下可以使我:
>>> $species->subfamily
BadMethodCallException with message 'Call to undefined method App/Models/Species::hasOneThrough()'
但是以某种方式在$ subfamily-> species关系中使用hasManyThrough()可以正常工作!
答案 0 :(得分:0)
您需要升级到Laravel 5.8
才能使用hasOneThrough()
。希望对您有所帮助!编码愉快。
答案 1 :(得分:0)
您使用的是哪个laravel版本? Laravel 5.8中是否引入了一个通行证