繁体   English   中英

如何从Laravel中的关系获取数据?

[英]How to get data from a relationship in Laravel?

我有一个业务模型和订阅模型。 我用以下内容加载数据:

Business::with('subscriptions')->get()

然后,我在Business类上创建了一个方法,如下所示:

public function check_for_subscription($type)
{
    if($this->subscriptions->isEmpty() === false)
    {
        foreach($this->subscriptions as $subscription)
        {
            dd($subscription);
            if($subscription->type == $type)
            {
                return true;
            }
        }
    }
    return false;
}

dd向我显示以下内容:

object(Subscription)#175 (17) {
  ["connection":protected]=>
  NULL
  ["table":protected]=>
  NULL
  ["primaryKey":protected]=>
  string(2) "id"
  ["perPage":protected]=>
  int(15)
  ["incrementing"]=>
  bool(true)
  ["timestamps"]=>
  bool(true)
  ["attributes":protected]=>
  array(7) {
    ["id"]=>
    int(1)
    ["business_id"]=>
    int(1)
    ["type"]=>
    string(3) "614"
    ["starts_at"]=>
    NULL
    ["ends_at"]=>
    NULL
    ["created_at"]=>
    string(19) "0000-00-00 00:00:00"
    ["updated_at"]=>
    string(19) "0000-00-00 00:00:00"
  }
  ["original":protected]=>
  array(7) {
    ["id"]=>
    int(1)
    ["business_id"]=>
    int(1)
    ["type"]=>
    string(3) "614"
    ["starts_at"]=>
    NULL
    ["ends_at"]=>
    NULL
    ["created_at"]=>
    string(19) "0000-00-00 00:00:00"
    ["updated_at"]=>
    string(19) "0000-00-00 00:00:00"
  }
  ["relations":protected]=>
  array(0) {
  }
  ["hidden":protected]=>
  array(0) {
  }
  ["visible":protected]=>
  array(0) {
  }
  ["fillable":protected]=>
  array(0) {
  }
  ["guarded":protected]=>
  array(1) {
    [0]=>
    string(1) "*"
  }
  ["touches":protected]=>
  array(0) {
  }
  ["with":protected]=>
  array(0) {
  }
  ["exists"]=>
  bool(true)
  ["softDelete":protected]=>
  bool(false)
}

如果我尝试执行$subscription->type我什么也没得到。 关于如何使它起作用的任何想法?

这是我的商业模式的起点

class Business extends Eloquent 
{
    public function subscriptions()
    {
        return $this->hasMany('Subscription');
    }
}

这是我的订阅模式

class Subscription extends Eloquent 
{
    public function businesses()
    {
        return $this->belongsTo('Business');
    }
}

根据dd()输出,Subscription对象没有名为“ type”的属性。 这就解释了为什么您无法从$ subscription-> type中得到任何信息。

再次根据dd()输出,Subscription对象的确具有一个名为“ attributes”的受保护属性,该属性是一个数组。 该数组的键之一是“类型”,因此我假设这是您尝试达到的值。

由于“属性”数组受到保护,因此您无法从外部类访问它。 我假设您的Subscription类具有一个名为getAttributes()的getter函数,该函数返回受保护的数组。 如果是这样,那么您唯一需要的是:

public function check_for_subscription($type)
{
    if($this->subscriptions->isEmpty() === false)
    {
        foreach($this->subscriptions as $subscription)
        {
            $attributes = $this->subscriptions->getAttributes();
            if($attributes['type'] == $type)
            {
                return true;
            }
        }
    }
    return false;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM