如何使用这样的 SQL 查询创建 laravel 关系模型
How to create a laravel relationship model with a SQL query like this
我有这样的查询
SELECT * FROM 'discussions' INNER JOIN comments ON comments.commentable_id = discussions.id WHERE discussions.user_id = 1 ORDER BY comments.id DESC
如何在 laravel 模型中创建关系
不适用于这样的查询生成器
DB::table('discussions')
->join('comments', 'comments.commentable_id', '=', 'discussions.id')
->where('discussions.user_id', '=', 1)
->orderBy('comments.id', 'DESC')
->get();```
首先你需要知道这是什么类型的关系。
One:One
、One:Many
、Many:Many
、Many:One
之后你可以看看documentation
您可以通过在终端中调用 php artisan make:model <name>
或手动创建它们来创建 2 个模型。
之后,您只需执行文档告诉您的操作即可。
假设您有 one-to-many,其中一个讨论有很多评论,如果它是 non-conventional 命名,则在第二个参数中指定 foreign_key 很重要。
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Discussion extends Model
{
/**
* Get the comments for the discussions post.
*/
public function comments()
{
// Watch the foreign_key in this instance 'commentable_id'
return $this->hasMany(Comment::class, 'commentable_id');
}
}
之后你可以调用
$comments = Discussion::where('user_id', 1)->first()->comments
获取属于该讨论的所有评论
我不想成为一个混蛋,但是 documentation 确实是一个很好的信息来源。我建议您在开始开发之旅之前阅读所有内容。
我有这样的查询
SELECT * FROM 'discussions' INNER JOIN comments ON comments.commentable_id = discussions.id WHERE discussions.user_id = 1 ORDER BY comments.id DESC
如何在 laravel 模型中创建关系
不适用于这样的查询生成器
DB::table('discussions')
->join('comments', 'comments.commentable_id', '=', 'discussions.id')
->where('discussions.user_id', '=', 1)
->orderBy('comments.id', 'DESC')
->get();```
首先你需要知道这是什么类型的关系。
One:One
、One:Many
、Many:Many
、Many:One
之后你可以看看documentation
您可以通过在终端中调用 php artisan make:model <name>
或手动创建它们来创建 2 个模型。
之后,您只需执行文档告诉您的操作即可。
假设您有 one-to-many,其中一个讨论有很多评论,如果它是 non-conventional 命名,则在第二个参数中指定 foreign_key 很重要。
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Discussion extends Model
{
/**
* Get the comments for the discussions post.
*/
public function comments()
{
// Watch the foreign_key in this instance 'commentable_id'
return $this->hasMany(Comment::class, 'commentable_id');
}
}
之后你可以调用
$comments = Discussion::where('user_id', 1)->first()->comments
获取属于该讨论的所有评论
我不想成为一个混蛋,但是 documentation 确实是一个很好的信息来源。我建议您在开始开发之旅之前阅读所有内容。