[英]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.