Phalcon 关系 return 错误

phalcon relationship return false

我想在用户 table 和产品 table 之间建立关系,但结果 returns 错误 这是用户模型:

class Users extends \Phalcon\Mvc\Model
{
public $id;
public $name;
public $password;
 public $email;

 public function initialize()
    {
        $this->setSchema("asulaiman");
        $this->setSource("users");

        $this->hasMany(
            'id',
            'Products',
            'product_id'
        );}}

这是我的产品型号:

class Products extends \Phalcon\Mvc\Model
{
    public $id;
    public $user_id;
    public $name;

    public function initialize()
    {
        $this->setSchema("asulaiman");
        $this->setSource("products");

         $this->belongsTo(
            'product_id',
            'Users',
            'id'
        );}}

和这个查询:

public function showAction($id)
{
    $get_product = Products::findFirst('id = ' . $id);
    if (!empty($get_product)) {
        $this->response->setJsonContent(array('data' => $get_product->users));
return $this->response; 
}}

这个结果 returns :

任何帮助请

这就是找不到关系时发生的情况。

我假设您的用户拥有许多产品,并且这些产品属于用户。您在 Products 模型上的代码所说的是 Products 模型上的 products_id 字段与 User 模型上的 id 字段相关。

问题是 Products 模型上没有 product_id 字段。

 $this->belongsTo(
    'user_id' // "id" field on the Products model
    'Users', // The model I want
    'id'// The field I want on that model (Users.id)
);

你在做什么并没有多大意义。除了解释这些关系是如何工作的之外,如果没有看到架构,我真的无法为您提供进一步的帮助。

问题是您正在尝试检索产品的 属性 用户:$get_product->users 但产品没有用户(只有 ID、user_id 和名称) ;

首先你必须检索 user_id:

$product = Products::FindFirstById($id);
$user = Users::FindFirstById($product->user_id);

您也可以一步完成,但这样更清楚。