我有一些模型属于活动模型。
在我的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;
因为我真的不知道为什么......
请有人帮助我,对不起我的英语不好。谢谢。 (如果您需要任何其他代码,请告诉我。)
答案 0 :(得分:0)
我的型号代码:
<?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');
}
}
答案 1 :(得分:0)
我找到了为什么我的模型查询无法工作的原因,因为&#34; _&#34;在函数名称中。
只需更改
public function serial_codes()
到
public function serialcodes()
然后一切都会好起来的。
感谢大家。