简体   繁体   English

laravel 4 hasOne / hasMany / belongsTo不起作用

[英]laravel 4 hasOne/ hasMany / belongsTo doesn't work

I have some models belong to Activity Model. 我有一些模型属于活动模型。

in my Activity.php I had 在我的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');
     }

}

and in SerialCode.php, I had 在SerialCode.php中,我有

<?php

class SerialCode extends \Eloquent {
     protected $fillable = ['code'];

     public function activity()
     {
         return $this->belongsTo('Activity');
     }
}

and in my controller, when I wrote 在我的控制器中,当我写

$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);

it works. 有用。

But when it turns to 但是当它变成

//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;

for I really don't know why... 因为我真的不知道为什么...

Can anybody help me please, and sorry for my poor English. 有人可以帮我吗,对不起我的英语不好。 Thank You. 谢谢。 (If you need any code else please tell me.) (如果您需要其他代码,请告诉我。)

my model code: 我的模型代码:

<?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');
       }  
}

I found the reason that why my model query cannot work, because the "_" in function name. 我发现了为什么我的模型查询无法工作的原因,因为函数名称中的“ _”。

just change 只是改变

public function serial_codes()

to

public function serialcodes()

then everything will go fine. 那么一切都会好起来的。

Thank to everybody. 谢谢大家。

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

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