[英]Laravel - Access to relations array
I try to access the relationship array but I am getting an error. 我尝试访问关系数组但我收到错误。
This this my Campaign Model : 这是我的竞选模型:
class Campagne extends Model
{
protected $table = 'Campagne';
/**
* The primary key for the model.
*
* @var string
*/
protected $primaryKey = 'Id';
public $incrementing = false;
public function Annonceur()
{
return $this->belongsTo('App\Annonceur', 'Annonceur');
}
}
In my database i have the good foreign key and in my debugbar I have this object : 在我的数据库中,我有很好的外键,在我的调试栏中我有这个对象:
0 => Campagne {#574 ▼
#table: "Campagne"
#attributes: array:12 [▼
"Id" => 7
"Nom" => "ORANGE"
"DateDebut" => null
"DateFin" => null
"Annonceur" => 25
"Service" => 25
"Description" => null
"Active" => null
"Visible" => 1
"CommerceMaj" => null
"created_at" => "2019-04-27 15:00:43"
"updated_at" => "2019-04-27 15:00:43"
]
#relations: array:1 [▼
"Annonceur" => Annonceur {#610 ▼
#table: "Annonceur"
#primaryKey: "Id"
#fillable: array:12 [▶]
#connection: "mysql"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:17 [▶]
#original: array:17 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
]
}
I have to access the "Annonceur" relation attribute but I have an error when I try : 我必须访问“Annonceur”关系属性,但我尝试时出错:
$campagne->Annonceur->Name
for exemple. $campagne->Annonceur->Name
例如。
Thanks 谢谢
The relationship you have defined using 您使用定义的关系
return $this->belongsTo('App\\Annonceur', 'Annonceur');
is called Many to Many
relationship. 被称为Many to Many
关系。
That means, you are telling to Laravel that your campagne
has many Annonceur
. 这意味着,你告诉Laravel你的campagne
有很多Annonceur
。 as a result when you access $campagne->Annonceur
it return a collection(for simplicity let's thing it is an array) of Annonceur
instead of a single instance of Annonceur
. 当你访问一个结果$campagne->Annonceur
它返回一个集合(为简单起见让我们的东西它是一个数组)的Annonceur
,而不是单个实例Annonceur
。 So, either you can loop through all those Annonceur
using a for loop as below: 所以,你可以使用for循环遍历所有Annonceur
,如下所示:
foreach($campagne->Annonceur as $annonceur){
dd($annonceur->Name);
}
or to access only the first annonceur
you can access as below: 或者只访问您可以访问的第一个annonceur
,如下所示:
$campagne->Annonceur->first()->Name;
If you change the relation to one to one
means using 如果将关系更改one to one
意味着使用
$this->hasOne('App\\Annonceur', 'Id', 'Annonceur');
then you can access like: $campagne->Annonceur->Name;
那么你可以访问如下: $campagne->Annonceur->Name;
If your defined relationship is correct. 如果您定义的关系是正确的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.