dongqian5569 2016-11-17 02:37
浏览 71
已采纳

Laravel Relation Query / Find - 尝试获取非对象的属性

I'm not able to fix this error when I tried associate category to transaction.

// TransactionController

$transactions = DB::table('transactions')
        ->where('status', 'false')
        ->orderBy('date','asc')
        ->get();        

        foreach($transactions as $data) {
            $transaction = new Transaction();
            $transaction->id = $data->id;
            $transaction->category = Transaction::find($data->categories_id)->category;
            $transaction->description = $data->description;
    }

The error occurs at time: ErrorException in TransactionController.php line 80: Trying to get property of non-object

Line 80: $transaction->category = Transaction::find($data->categories_id)->category;

But, if I test my code with die, that's result:

die(Transaction::find($data->categories_id)->category()->first());

{"id":1,"users_id":1,"description":"Alimenta\u00e7\u00e3o","created_at":"2016-11-15 20:31:11","updated_at":"2016-11-15 20:31:11"}

// Transaction Model

class Transaction extends Model
{
    public function category(){
        return $this->hasOne('App\Category','id');
    }  

[]'s

  • 写回答

1条回答 默认 最新

  • douhanzhen8927 2016-11-17 03:15
    关注

    You are getting that error as one or multiple $data->categories_id are not matching the id on the transactions table.

    Note: It's not a good practice to find a model and call a function on it on the same line as you have done.

    Transaction::find($data->categories_id)->category;

    Because, you never know what id will be passed as argument to find(). Better go for findOrFail().

    $tran = Transaction::findOrFail($data->categories_id);
    
    $cat = $tran->category;
    

    The findOrFail() function will throw a ModelNotFoundException whenever the id doesn't match in the transactions table. This exception can be easily handled by try...catch block.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C#读写EXCEL文件,不同编译
  • ¥15 如何提取csv文件中需要的列,将其整合为一篇完整文档,并进行jieba分词(语言-python)
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置