![](/img/trans.png)
[英]laravel 5.4 belongsTo and hasMany does't work with 2 foreign key
[英]laravel 4 hasOne/ hasMany / belongsTo doesn't work
我有一些模型屬於活動模型。
在我的Activity.php中
<?php
class Activity extends \Eloquent {
protected $fillable = [];
public function activity_car_nums()
{
return $this->hasMany('ActivityCarNum');
}
public function newables()
{
return $this->hasMany('Newable');
}
public function serial_codes()
{
return $this->hasMany('SerialCode');
}
public function applys()
{
return $this->hasMany('Apply');
}
}
在SerialCode.php中,我有
<?php
class SerialCode extends \Eloquent {
protected $fillable = ['code'];
public function activity()
{
return $this->belongsTo('Activity');
}
}
在我的控制器中,當我寫
$serial_codes = [];
while(count($serial_codes) < $serial_code_total)
{
$code = substr(md5(uniqid(rand(), true)),0,5);
$serial_code = new SerialCode(['code' => $code]);
if(!in_array($serial_code, $serial_codes))
{
$serial_codes[] = $serial_code;
}
}
$activity->serial_codes()->saveMany($serial_codes);
有用。
但是當它變成
//this can get activity object
$activity = Activity::find($id);
//this can get the serial codes of the object above.
$serial_codes = SerialCode::whereActivityId($id)->get();
//this don't work, it returns null
$serial_codes = $activity->serial_codes;
因為我真的不知道為什么...
有人可以幫我嗎,對不起我的英語不好。 謝謝。 (如果您需要其他代碼,請告訴我。)
我的模型代碼:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use DB;
class Product extends Model
{
public $table="s_products";
protected $primaryKey = 'product_id';
public function reviews()
{
return $this->hasMany('App\ProductReview');
}
public function attributes()
{
return $this->hasMany('App\AttributeMapping');
}
public function images()
{
return $this->hasMany('App\Image');
}
}
我發現了為什么我的模型查詢無法工作的原因,因為函數名稱中的“ _”。
只是改變
public function serial_codes()
至
public function serialcodes()
那么一切都會好起來的。
謝謝大家。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.